在Typescript中将类型变量限制为文字类型



考虑以下代码:

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
}

类似的内容。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>

最新更新