我想创建一个 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;
}
我在上面尝试过的两种方法(使用映射类型和接口(interface))没有达到我想要的效果。有人可以帮忙吗?
最佳答案
您可以使用 ?
使键成为可选的,所以
interface Partial {
a?: boolean;
b?: boolean;
c?: boolean;
}
或者,您可以这样做:
type Keys = "a" | "b" | "c";
type Test = {
[K in Keys]?: boolean
}
关于javascript - typescript 对象 : How do I restrict the keys to specific strings?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47251559/