Typescript对象:如何将键限制为特定字符串?

时间:2017-11-12 17:11:41

标签: javascript string typescript object key

我想创建一个Partial类型的对象,其中的键将是' a',' b'或' c&#的某种组合39 ;.它不会有所有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;
}

我上面尝试的两种方法(使用映射类型和接口)无法达到我想要的效果。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:7)

您可以使用?使密钥可选,因此

interface Partial {
   a?: boolean;
   b?: boolean;
   c?: boolean;
}

或者,你可以这样做:

type Keys = "a" | "b" | "c";

type Test = {
    [K in Keys]?: boolean
}