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}
在代码中。我只使用 typeKey
作为另一种类型的属性名称。为什么Key
必须是一个值?
解决方案
您可能应该使用表单的映射类型{[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 symbol
value
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
值......所以上面的映射类型是推荐的方法。
推荐阅读
- amazon-web-services - 将标签添加到 VPC 的默认网络 ACL
- html - 循环本地存储并显示离子应用程序中所有键和值的完整列表
- flutter - Flutter 应用程序部署到 App Store 被拒绝,并出现以下错误 -
- javascript - 如何在 JavaScript 中检测 Android 浏览器上已选择文本?
- opentest - OpenTest:如何将 Opentest 与 linux jenkins 服务器集成?
- oauth-2.0 - 使用 MFA 为 Azure AD 用户执行密码授权身份验证
- express - 我可以使用 Express res.sendFile() 发送 XLS/XLSX 文件吗?
- javascript - 如何将我的 expo 应用程序发布到 Apple 应用商店?
- json - 将 pandas 数据帧转换为具有特定格式的 json
- javascript - 如何在产品列表中添加切换“全部显示”、“全部隐藏”