【问题标题】:Use of coalescing operator in Typescript [duplicate]在 Typescript 中使用合并运算符 [重复]
【发布时间】:2021-07-16 20:57:39
【问题描述】:

我需要格式化可以包含多种类型的数组元素:

interface OptionType {
  value: string | number | boolean
  label?: string | number | boolean
}
const inputArray : Array<number | string | boolean | OptionType> = [1, 2, { value: 3, label:'test' }]

我需要我的新数组的所有元素都是 OptionType 类型,所以我使用了这个:

const formattedArray = inputArray.map((option)=>({
  value : option.value ?? option,
  label: option.label ?? option.value?? option
}))

但是,我不断收到 Typescript 错误,例如“类型 'string' 上不存在属性 'label'”,我知道,这就是我为此使用 Null Coalescing Operator 的原因。

我之前尝试过使用基本检查:

 if (typeof option === 'string' || typeof option === 'number' || typeof option === 'boolean')

它有效,但我基本上失去了 ?? 的效用运算符。

是我遗漏了什么还是只是 Typescript 的正常操作?

【问题讨论】:

  • 输入了一个答案,但问题在发布之前就关闭了,请查看打字稿文档typescriptlang.org/docs/handbook/advanced-types.html 和用户定义的类型保护部分中的此页面。像这样的东西会起作用。 value : (option as OptionType).value ??选项,

标签: javascript typescript


【解决方案1】:

直接回答您的问题:这是目前 TypeScript 的限制。请参阅此 GitHub 问题以阅读有关相关讨论的更多信息:https://github.com/microsoft/TypeScript/issues/1260

这是您的示例的重构,它将满足编译器:

type BNS = boolean | number | string;

interface OptionType {
  value: BNS;
  label?: BNS;
}

const inputArray : Array<BNS | OptionType> = [1, 2, { value: 3, label:'test' }];

const formattedArray = inputArray.map(option => ({
  value : typeof option === 'object' ? option.value : option,
  label: typeof option === 'object' ? option.label ?? option.value : option,
}));

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2010-10-12
    • 2016-03-19
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2021-10-24
    • 2014-09-23
    • 2013-06-11
    相关资源
    最近更新 更多