请考虑以下代码:
type T<A> = {
[A]: true
}
鉴于这种类型,我想这样使用它:
type Obj = T<"key">
若要生成与此类型等效的类型,请执行以下操作:
type Obj = {
key: true
}
但是,编译器给了我一个错误:A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
我能否以某种方式证明,A
类型变量只能通过字符串文本来实现?类似于:
type T<A extends ?literal?> = {
[A]: true
}
发布于 2022-01-13 09:39:58
就像这样。A extends keyof any
并不完全是文字类型,因此我们需要在这里使用映射类型。
type T<A extends keyof any> = {
[K in A]: true;
};
// It's equivalent to built-in Record type, so you should probably use it
// type T<K extends keyof any> = Record<K, true>
https://stackoverflow.com/questions/70694230
复制相似问题