Typescript接口通用属性名称
假设我们有两个变量Typescript接口通用属性名称,typescript,interface,properties,typescript-typings,Typescript,Interface,Properties,Typescript Typings,假设我们有两个变量 const x='property1' 常数y='property2' 我们有功能 function foo<key extends keyof MapInterface>(name: key, props: (MapInterface[key])) 是否可以像调用变量x,y那样一般地创建接口 interface MapInterface{ x:any; //return 'property1':any; y:any; //return 'property2'
const x='property1'
常数y='property2'
我们有功能
function foo<key extends keyof MapInterface>(name: key, props: (MapInterface[key]))
是否可以像调用变量x,y那样一般地创建接口
interface MapInterface{
x:any; //return 'property1':any;
y:any; //return 'property2':any;
}
是的,从TypeScript 2.7开始,您可以使用pull请求中引入的。您唯一缺少的是需要使用(属性名称必须用括号括起来):
希望有帮助。祝你好运 问题的可能重复之处在于x和y是从一个单独的类导入的,因此这些值将在运行时而不是编译时被接口访问。所以,不幸的是,它拒绝了这种方法。您应该能够在编译时在单独的类中访问它们,但我当然不知道您的设置。。。如果你想要一个更有针对性的答案,你应该用相关信息编辑你的问题;上述答案确实适用于您目前提出的问题。
interface MapInterface{
x:any; //return 'property1':any;
y:any; //return 'property2':any;
}
const x = 'property1'
const y = 'property2';
interface MapInterface {
[x]: any;
[y]: any;
}
declare const mapInt: MapInterface;
mapInt[x]; // works
mapInt[y]; // works
mapInt.property1; // also works
mapInt.property2; // also works