typescript - 如何使用字符串数组作为接口的键?
问题描述
假设我有这个字符串数组:
const claims = ['val1','val2','val3','val4', ...]
如何根据以下值构建接口claims
:
interface Claims {
val1: boolean
val2: boolean
val3: boolean
val4: boolean
...
}
我正在使用 Typescript 3.7.x
我试着玩这个答案:https ://stackoverflow.com/a/46344193/1439748
interface Claims{ [key in claims[number]]?: boolean }
但收到这些错误:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1169)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
'number' only refers to a type, but is being used as a value here.ts(2693)
解决方案
事实证明,您的代码将通过进行以下 3 项更改来工作:
- 放在
as const
数组文字之后,以便claims
推断为(只读)元组 - 使用(类型空间)
typeof
运算符claims[number]
- 而不是
interface
使用类型别名与对象类型文字相结合;事实证明,接口不起作用,而对象类型文字会。
我最终得到以下代码:
const claims = ['val1','val2','val3','val4'] as const;
type Claims = {
[key in typeof claims[number]]?: boolean
}
推荐阅读
- typescript - 使用与联合成员匹配的键创建对象
- reactjs - ReactJS 从上面的元素获取图像
- macos - 终端中的 SWI prolog 与 SWI 软件下载不同。操作系统
- c# - MigraDoc 单元格背景颜色问题
- php - 如何列出由草稿与已发布过滤的所有文字新闻页面及其 URL?
- angularjs - 如何监视我正在测试的服务的功能?
- r - 如何减去构造相同长度向量的列表
- ruby-on-rails - 如何使用水豚检查特定 html 元素中的 css 类名?
- google-apps-script - 谷歌表格 - 希望在输入日期超过今天的日期后隐藏行
- c# - c#在公共静态类中循环