TypeScript:类型“ T”上不存在属性“ propertyName”

时间:2020-06-22 15:13:52

标签: typescript typescript-typings typescript-generics

当前我正在学习TypeScript,但遇到一个问题:“ 类型'T'上不存在属性'值'

这是我的代码:

type ParseType = <T>(value: T, opts: any, useRounding: boolean) => number;
const parse: ParseType = function(value, opts: any, useRounding): number {
//...
if (isNumber || value instanceof currency) {
  v = (isNumber ? value : value.value) * precision;
}
//...

我将非常感谢您的帮助:)

UPD:我刚刚添加了新接口interface Currency {value?: number;},使我的通用类型对其进行了扩展:type ParseType = <T extends Currency>(value: T, opts: any, useRounding: boolean) => number;,并按照注释中的建议编写了两个单独的条件。

1 个答案:

答案 0 :(得分:1)

我猜currency总是包含一个value道具? Typescript无法推断出这一点,因为您使用的是两个嵌套的条件语句-从理论上讲可以,但是不够聪明。在内部三元条件下,Typescript不知道!isNumber也意味着instanceof currency的事实-该连接已丢失。 isNumber也会发生同样的情况-即使您通过检查value是否在某个时候得到这个布尔值,但如果您在类型中的其他地方使用它,这种类型推断属性也不会保留有条件的。为了让Typescript推断类型,必须在条件中立即进行检查。

尝试以下操作(将嵌套条件分为两个独立的条件):

if (typeof value === 'number') {
  v = value * precision;
} else if (value instanceof currency) {
  v = value.value * precision;
}

一个简短的例子:

function abc<R>(v: R) {
  if (typeof v === 'number') {
    // Typescript knows v is a number
  }

  const isNumber = typeof v === 'number';
  if (isNumber) {
    // Typescript knows nothing about v
  }
}