Typescript接口通用属性名称

时间:2018-09-07 16:32:22

标签: typescript interface properties typescript-typings

说我们有两个变量

const x='property1' const y='property2'

我们有功能

function foo<key extends keyof MapInterface>(name: key, props: (MapInterface[key]))

此界面应类似于

interface MapInterface{
'property1':any;
'property2':any;
}

是否可以像调用变量x,y那样通用地创建接口

interface MapInterface{
x:any; //return 'property1':any;
y:any; //return 'property2':any;
}

1 个答案:

答案 0 :(得分:0)

是的,您可以使用类型为constant-named properties的TypeScript 2.7以及在请求请求Microsoft/TypeScript#15473中引入的方法来执行此操作。唯一缺少的是您需要使用computed property syntax(属性名称必须用括号括起来):

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

希望有帮助。祝你好运!

相关问题