【问题标题】:Type with computed property using 'in' from type使用类型中的“in”键入具有计算属性的类型
【发布时间】:2018-10-10 05:24:21
【问题描述】:

我使用 typeofkeyof 从对象 Options 生成类型 Option

我定义了另一种类型 - Dropdown,它具有计算属性并使用 Option 使用 in

我得到一个错误:

类型 '{ [Options.option1]: string; 中缺少属性 'options2' }'。

我应该如何正确实施?

const Options = {
  option1: 'option1' as 'options1',
  option2: 'option1' as 'options2',
  option3: 'option1' as 'options3',
}

type Option = typeof Options[keyof typeof Options];
type Dropdown = { [key in Option]: string };

const obj: Dropdown = {
  [Options.option1]: 'test'
}

playground

【问题讨论】:

  • 目标是Dropdown 中的属性是可选的?因为如果是这样,您只是缺少?{ [key in Option]?: string }
  • 好吧,真丢脸 :) 你是对的。谢谢!如果您愿意,请将其发布为答案,以便可能对其他笨拙的人有所帮助..

标签: typescript types computed-properties


【解决方案1】:

感谢@TitianCernicova-Dragomir,我只需要设置可选的属性 (?),如下所示:

const Options = {
  option1: 'option1' as 'options1',
  option2: 'option1' as 'options2',
  option3: 'option1' as 'options3',
}

type Option = typeof Options[keyof typeof Options];
type Dropdown = { [key in Option]?: string };

const obj: Dropdown = {
  [Options.option1]: 'test'
}

Playground

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2014-11-04
    • 2022-10-06
    • 1970-01-01
    • 2013-11-22
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多