文字类型作为另一种类型的键

lei*_* li 5 typescript

type Key = 'foo'  //'Key' only refers to a type, but is being used as a value here.

const Key = 'foo' // OK

type Test={[Key]:string}
Run Code Online (Sandbox Code Playgroud)

在代码中。我只使用 typeKey作为另一个类型的属性名称。为什么Key必须是一个值?

TS游乐场

jca*_*alz 5

您可能应该使用表单的映射类型{[P in KeyType]: ValueType}不是计算属性声明

type Test = { [K in Key]: string };
/* type Test = {
    foo: string;
} */
Run Code Online (Sandbox Code Playgroud)

在这种情况下,值类型不依赖于属性,您还可以使用内置Record<K, V>实用程序类型

type AlsoTest = Record<Key, string>;
/* type AlsoTest = {
    foo: string;
} */
Run Code Online (Sandbox Code Playgroud)

我找不到这方面好的规范文档,但在 TypeScript 中,计算属性声明的形式为{[value]: Type},其中是常量文字类型type的value的名称。作为一个值,必须在运行时存在:unique symbolvalue

const key: Key = 'foo';
type ComputedKeyTest = { [key]: string };
/* type ComputedKeyTest = {
    foo: string;
} */

const mySymbol = Symbol("mySymbol");
type ComputedSymbolKey = { [mySymbol]: string };
/* type ComputedSymbolKey = {
    [mySymbol]: string;
} */
Run Code Online (Sandbox Code Playgroud)

因为Key是一种类型,而不是一个值,所以如果您编写 ,则会出现错误{[Key]: string}key请注意,您可以通过使用而不是在此处获取所需的特定类型Key。但这仅适用于Key单个字符串文字,而不是此类文字的联合。即便如此,您不需要key仅仅为了进行类型操作而向 JavaScript 发出值...因此上面的映射类型是推荐的方法。

Playground 代码链接