【发布时间】:2021-04-09 03:24:15
【问题描述】:
是否可以根据传递的泛型类型定义属性名?
type Foo<T> = {
// magic goes here
someProp: boolean
};
enum MyEnum {
red = 'red',
blue= 'blue',
}
const d: Foo<MyEnum.blue> = null;
d.someProp
d.blue // Property 'blue' does not exist on type 'Foo<MyEnum.blue>'.ts(2339)
查看了所有文档,但我无法弄清楚。
【问题讨论】:
-
您是否只是在寻找the
Recordutility type 之类的内容,例如this? -
正是@jcalz,谢谢!有没有办法用接口而不是类型来做到这一点?
-
不,接口必须具有静态已知键。你可以写
interface XYZ extends Foo<MyEnum.blue> {},但你不能写interface XYZ<T extends PropertyKey> extends Foo<T> {}。
标签: typescript typescript-generics