Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property X does not exist on type Y when using static class property

Tags:

typescript

I'm having an issue with typescript error when I want to access a static class property in some module.

Let's say that I want to export some class with static property:

// MODULE 1
export class AppConfig {
  static readonly apiKey: string = process.env.API_KEY;
}

In module 2 I create an Interface for some object;

// MODULE 2
import { AppConfig } from "./appConfig";

interface AppContext {
  config: AppConfig;
  ...
}

export default class App {
 ...

 get ctx(): AppContext {
  return {
    config: AppConfig,
    ...
  };
 }

 ...
}

In module 3 I finally want to access the property:

// MODULE 3
...    
function createContext(app: App): object {
  return Object.assign(app.ctx, {
    apiContext: app.ctx.config.apiKey
  });
}
...

And then I get TS ERROR: "Property 'apiKey' does not exist on type 'AppConfig'.", which is quite strange, because the property is undoubtedly on this type.

like image 630
teddyS Avatar asked Sep 13 '25 11:09

teddyS


1 Answers

Static properties are not accessible via class instance. It should be accessed via class identifier like this:

const key = AppConfig.apiKey;

See Static Properties

like image 55
Pavel Agarkov Avatar answered Sep 15 '25 01:09

Pavel Agarkov