【问题标题】:Typescript object: How do I restrict the keys to specific strings?Typescript 对象:如何将键限制为特定字符串?
【发布时间】:2018-04-25 09:09:19
【问题描述】:

我想创建一个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;
}

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

【问题讨论】:

    标签: javascript string typescript object key


    【解决方案1】:

    您可以使用? 使键成为可选的,所以

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

    或者,您可以这样做:

    type Keys = "a" | "b" | "c";
    
    type Test = {
        [K in Keys]?: boolean
    }
    

    【讨论】:

    • 谢谢!有没有办法使用Keys 类型以编程方式执行此操作?另外,如果我需要要求至少存在一个键怎么办?
    • 如何限制至少一个键存在?
    • @the_lrner stackoverflow.com/a/59213781 应该有帮助
    猜你喜欢
    • 2021-11-21
    • 1970-01-01
    • 2017-09-28
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2022-06-25
    • 1970-01-01
    相关资源
    最近更新 更多