问题/答案 - 2021更新
这个问题是6年前提出的,当时我对TypeScript的理解非常有限! 我不想删除它,因为仍然有一些人在阅读这篇文章。
如果你想让一个变量的类型成为另一个变量的属性,你可以使用keyof
。
例如:
interface User {
name: string;
age: number;
}
const nameProperty: keyof User = 'name'; // ok
const ageProperty: keyof User = 'age'; // ok
const emailProperty: keyof User = 'email'; // not ok
如果你想要一个接受另一个参数的属性作为参数的方法,可以使用泛型将两种类型链接在一起。
示例,使用泛型和 keyof
:
const foo = <TObject extends object>(
object: TObject,
property: keyof TObject
) => {
// You can use object[property] here
};
foo({ a: 1, b: 2 }, 'a'); // ok
foo({ a: 1, b: 2 }, 'b'); // ok
foo({ a: 1, b: 2 }, 'c'); // not ok
使用泛型+Record
的示例:
const foo = <TKey extends string>(
object: Record<TKey, unknown>,
property: TKey
) => {
// You can use object[property] here
};
foo({ a: 1, b: 2 }, 'a'); // ok
foo({ a: 1, b: 2 }, 'b'); // ok
foo({ a: 1, b: 2 }, 'c'); // not ok
请勿使用此问题答案!如果您在某个时刻重命名属性,TypeScript将自动告诉您存在错误。
原始问题(2014年)
目标
我有一个 TypeScript 接口:
interface IInterface{
id: number;
name: string;
}
我有一些方法需要输入属性名称(字符串)
例如:
var methodX = ( property: string, object: any ) => {
// use object[property]
};
我的问题是,当我调用methodX
时,我必须以字符串的形式写入属性名称。
例如:methodX("name", objectX);
其中objectX实现了IInterface接口
但这是不好的:如果我重命名属性(假设我想将name
重命名为lastname
),则必须手动更新所有代码。
而我不想有这种依赖性。
由于TypeScript接口没有JS实现,因此我不知道如何不使用字符串。
我希望有一个像这样的解决方案:methodX(IInterface.name.propertytoString(), objectX);
我很新于JS,你能看到其他替代方案吗?
(可选)更多细节:为什么需要将属性作为参数传递,而不使用通用方法?
我使用链接数据的方法:
linkData = <TA, TB>(
inputList: TA[],
inputId: string,
inputPlace: string,
outputList: TB[],
outputId: string ) => {
var mapDestinationItemId: any = {};
var i: number;
for ( i = 0; i < outputList.length; ++i ) {
mapDestinationItemId[outputList[i][outputId]] = outputList[i];
}
var itemDestination, itemSource;
for ( i = 0; i < inputList.length; ++i ) {
itemDestination = inputList[i];
itemSource = mapDestinationItemId[itemDestination[inputId]];
if ( itemSource ) {
itemDestination[inputPlace] = itemSource;
}
}
};
但是TA和TB可以有很多不同的id,所以我不知道如何使它更加通用。
o => o.SomeProperty
,你需要像这样更新正则表达式[a-zA-Z]+\s=>\s[a-zA-Z]+\.([A-Za-z0-9]+)
然后使用return arr[2]
。该正则表达式基本上将属性名称放在一个组中,以便我们可以从arr
中提取它。 - The Muffin Man