Typescript:类属性的索引签名
在尝试动态访问静态和实例化的类属性时,我遇到了一个关于索引签名的错误。我发现很多人在网上谈论这个错误,但我还没能解决这个问题 我能够在一个简单的课堂上重现这个问题:Typescript:类属性的索引签名,typescript,Typescript,在尝试动态访问静态和实例化的类属性时,我遇到了一个关于索引签名的错误。我发现很多人在网上谈论这个错误,但我还没能解决这个问题 我能够在一个简单的课堂上重现这个问题: interface MyClassInterface { name: string; getInstanceProperty( propertyName: string ): string; getStaticProperty( propertyName: string ): number; } class MyCla
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
我发现可以通过在类中添加类型信息来避免getInstanceProperty()中的错误,如下所示:
class MyClass implements MyClassInterface {
[key: string]: any;
// ...
}
是否可以将其添加到类接口中?我还没做到。
我想我需要对静态属性进行类似的修改,但我不知道如何做。有什么想法吗
我已经把这段代码复制到了。您只需要启用noImplicitAny选项来显示错误
非常感谢 几年来,围绕这一问题一直存在争议。目前似乎不可能有静态索引签名
我认为绕过此限制的唯一方法是通过使用下面的类型断言让编译器知道您的类具有静态索引签名,从而帮助编译器
接口可索引{
[键:字符串]:任意;
}
类MyClass{
...
公共getStaticProperty(propertyName:string):编号{
返回(MyClass作为可索引)[propertyName];
}
...
}
另一种解决方案可以是:
class-MyClass{
公共静态myMethod(变量:any):字符串{
}
}
界面可转位{
[键:字符串]:任意;
}
导出常量MyExportedClass=MyClass作为可索引;
它工作得非常好。非常感谢,这将是一个很大的帮助。我还没有使用类型断言,但也许我应该研究一下。这似乎是一个相当强大的工具。