【问题标题】:How to define a Record with a union as keys but have optional keys too?如何将带有联合的记录定义为键但也有可选键?
【发布时间】:2021-11-21 03:28:48
【问题描述】:

这是我的字典:

type Words = 'man' | 'sun' | 'person'
type Dictionary = Record<Words,string>

Dictionary等于这种类型:

type Dictionary = {
    man: string;
    sun: string;
    person: string;
}

目标是让其他程序员知道应该使用 IDE 自动完成将巫婆单词添加到字典中。但它限制了他们添加其他可选词。我试过了,但结果根本不包含单词:

type Words = 'man' | 'sun' | 'person' | string
type Dictionary = Record<Words,string>
// Equals to 
type Dictionary = {
    [x: string]: string;
}

我怎样才能让单词自动完成,但也可以有可选单词?

【问题讨论】:

    标签: typescript type-definition


    【解决方案1】:

    一种解决方案是明确定义字典,而不使用 Record 和 Union 类型。就像这样:

    type Dictionary = {
      man: string;
      sun: string;
      person: string;
      [word:string]:string;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2021-12-26
      • 2010-11-02
      • 1970-01-01
      相关资源
      最近更新 更多