Encountering a problem with index signatures while attempting to access static and instantiated class properties dynamically. Despite researching solutions online, I have been unable to resolve the issue.
The problem was replicated on a simple class:
interface MyClassInterface {
name: string;
getInstanceProperty( propertyName: string ): string;
getStaticProperty( propertyName: string ): number;
}
class MyClass implements MyClassInterface {
public name: string;
private static age: number;
public constructor( theName: string, theAge: number ) {
this.name = theName;
MyClass.age = theAge;
}
public getInstanceProperty( propertyName: string ): string {
return this[propertyName];
// Typescript error:
// Element implicitly has an 'any' type because type 'MyClass' has no index signature.
}
public getStaticProperty( propertyName: string ): number {
return MyClass[propertyName];
// Typescript error:
// Element implicitly has an 'any' type because type 'typeof MyClass' has no index signature.
}
}
const myClass = new MyClass( "John", 35 );
console.log(
myClass.getInstanceProperty( "name" ),
myClass.getStaticProperty( "age" )
); // Outputs "John 35" in the console
Introducing type information inside the class solves the error for getInstanceProperty() as shown below:
class MyClass implements MyClassInterface {
[key: string]: any;
// ...
}
Is it possible to include this modification in the class interface? I have not found a way to do it so far. A similar adjustment may be needed for static properties, but I am unsure how to proceed. Any suggestions?
I have set up this code in the TypeScript Playground. Make sure to enable the noImplicitAny option to see the errors.
Thank you!