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.
Static properties are not accessible via class instance. It should be accessed via class identifier like this:
const key = AppConfig.apiKey;
See Static Properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With