【发布时间】:2019-03-10 14:35:21
【问题描述】:
我想知道是否可以在 TS 中强制执行泛型的属性类型。我只想允许传递具有“字符串”属性的对象类型的泛型。例如,如果传递的通用接口包含数字或符号属性,则会引发错误。
这是我尝试并评论了我正在寻找的行为的POC:
class Test<T extends {[key: string]: any}>{
private data: T;
public getValue<K extends keyof T>(key: K): T[K] {
return this.data[key];
}
}
// the property is a string = ok
const okay = new Test<{ "aString": string }>();
// the property is a number = should raise an error
const shouldFail = new Test<{ 0: string }>();
【问题讨论】:
-
@bugs 情况不同,11315131 不包括扩展另一个接口。
标签: typescript