the*_*ner 6 javascript string key object typescript
我想创建一个类型的对象Partial,其中键将是'a','b'或'c'的某种组合.它不会有所有3个键(编辑:但它至少会有一个).如何在Typescript中强制执行此操作?这里有更多细节:
// I have this:
type Keys = 'a' | 'b' | 'c'
// What i want to compile:
let partial: Partial = {'a': true}
let anotherPartial: Partial = {'b': true, 'c': false}
// This requires every key:
type Partial = {
[key in Keys]: boolean;
}
// This throws Typescript errors, says keys must be strings:
interface Partial = {
[key: Keys]: boolean;
}
Run Code Online (Sandbox Code Playgroud)
我上面尝试过的两种方法(使用映射类型和接口)无法达到我想要的效果.有人可以帮忙吗?
你可以使用它?来使键可选,所以
interface Partial {
a?: boolean;
b?: boolean;
c?: boolean;
}
Run Code Online (Sandbox Code Playgroud)
或者,你可以这样做:
type Keys = "a" | "b" | "c";
type Test = {
[K in Keys]?: boolean
}
Run Code Online (Sandbox Code Playgroud)