【问题标题】:how to define the types of a part of the properties of an object literal?如何定义对象字面量的一部分属性的类型?
【发布时间】:2020-09-06 14:43:37
【问题描述】:

这里我有以下代码

const selectOptions = {
  mode: isTag ? 'tags' : 'combobox',
  ... //other stuff
}

return (<Select {...selectOptions}>...</Select>);

mode 被 TypeScript 推断为字符串,但 Select 只接受 type ModeOption = "default" | "multiple" | "tags" | "combobox",因此出现错误。

我目前的方法是mode: (isTag ? 'tags' : 'combobox') as ModeOption。但是我想避免使用 as,有没有更好的方法?如何定义一个对象字面量只有几个属性的类型?

【问题讨论】:

  • 你可以访问 Select 的 props 类型吗?然后你可以做例如const selectOptions: SelectProps = { ... }.

标签: typescript antd


【解决方案1】:

对于想要避免自动类型扩展的一般情况,可以使用as const

const selectOptions = {
  mode: (isTag ? 'tags' as const : 'combobox' as const),
}

as 的其他用法不同,它表明您正在根据编译器无法获得的额外信息断言类型,as const 不是潜在的类型不安全 - 它所做的只是告诉 TS 不要加宽类型,所以不要害怕使用它。

【讨论】:

  • 谢谢!但是有没有一种通用的方法来定义一个对象字面量的一个属性,让 ts 推断其余的?
  • 仅在 mode 属性上使用 as const 将起作用。如果您有额外的属性foo: 5,TS 将推断foo 属性为number
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2022-08-09
  • 2011-10-02
  • 1970-01-01
  • 2021-03-27
  • 2020-04-14
  • 1970-01-01
相关资源
最近更新 更多