typescript - 你能从只读字符串元组中获得字符串文字的联合吗?
问题描述
我想创建一个描述这样结构的接口......
const myObject: MyInterface = {
keys: ['a', 'b', 'c'], //Arbitrary length and string literals, array is readonly
props: {
a: null //OK
b: null //OK
c: null //OK
d: null //Invalid, 'd' is not in keys tuple
}
}
据我所知,TypeScript 在编译时推断这一点应该没有问题,因为键数组不能更改并且只有字符串文字。这是我目前尝试过的:
interface MyInterface {
readonly keys: readonly string[];
readonly props: Record<this['keys'][number],any>;
}
这只设法推断出键必须是字符串,而不是它们必须与给定的文字匹配。有什么办法可以完成我真正想要的吗?
解决方案
它在这里更容易使用type
,而不是interface
.
type Result<T extends ReadonlyArray<string>> = {
keys: T
} & {
[P in T[number]]: any // you can put here any type
};
type Test = Result<['a', 'b', 'c']>
const test: Test = {
keys: ['a', 'b', 'c'],
a: 1,
b: 2,
c: 3,
d: 3 // error
}
推荐阅读
- javascript - javascript - 具有键/值对的数组
- php - PDF 多数字标牌
- python - 如何将所有数据框行的某些列附加到另一个
- python-3.x - 在 Django 的 rest 框架中,如何关闭序列化程序中某些字段的验证?
- python - 产品变体未反映 Django 电子商务项目中订单摘要中的更新数量
- android-studio - 错误:指定的语言版本太高。支持的最高语言版本是 2.8。在android studio中我该如何解决?
- python - Django:在 Django 模板引擎中将 uuid 值转换为字符串
- ios - self.navigationItem.rightBarButtonItem = 按钮不起作用?
- c++ - Passing Map by Reference Conflicting Messages
- angular - 在类中没有实际变量的 for 循环中使用 ngModel