首页 > 解决方案 > 文字类型作为另一种类型的键

问题描述

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}

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

TS游乐场

标签: typescript

解决方案


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

type Test = { [K in Key]: string };
/* type Test = {
    foo: string;
} */

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

type AlsoTest = Record<Key, string>;
/* type AlsoTest = {
    foo: string;
} */

我找不到一个好的规范文档,但是在 TypeScript 中,计算属性声明的形式是{[value]: 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;
} */

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

Playground 代码链接


推荐阅读