【问题标题】:TS2339: Property 'value' does not exist on 'string | SelectValue'TS2339:“字符串”上不存在属性“值”|选择值'
【发布时间】:2020-07-28 14:41:47
【问题描述】:

我试图从对象中获取价值,但是,TypeScript 不明白我在做什么。 这是一段代码:

interface SelectValue {
  label: string;
  value: number;
}

interface FormValues {
  entity: SelectValue | string;
}

const makeFullDataObject = (formValues: FormValues) => ({
  entity: formValues.entity.value || formValues.entity,
});

错误提示:

TS2339: Property 'value' does not exist on type 'string | SelectValue'.   Property 'value' does not exist on type 'string'.

我知道这个属性在字符串类型上不存在,这就是我放置 OR 字符串的原因。这在 JavaScript 中工作得很好,但 TypeScript 不会让我编译它。任何不使用any 的解决方案?谢谢

【问题讨论】:

  • string 类型不包含 value 属性,只有 SelectValue 包含,这就是您收到错误的原因

标签: typescript


【解决方案1】:

您没有为 TypeScript 提供足够的信息。就它而言,formValues.entity 可以是一个字符串,因此没有value 属性。您应该尝试缩小其类型。这是一个例子:

function isSelectValue(entity: string | SelectValue): entity is SelectValue {
  return typeof (entity as any).value === 'string';
}

然后:

const makeFullDataObject = (formValues: FormValues) => ({
  entity: isSelectValue(formValues.entity) ? formValues.entity.value : formValues.entity,
});

【讨论】:

  • 好吧,那好吧。我真的希望我可以避免这种手动类型检查并让 TS 解决。
猜你喜欢
  • 1970-01-01
  • 2021-06-03
  • 2016-03-29
  • 2018-11-23
  • 2018-08-27
  • 2019-08-05
  • 2021-06-21
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多