如何让TypeScript理解类型检查?

bbuxkriu  于 2023-03-04  发布在  TypeScript
关注(0)|答案(2)|浏览(159)

我在TypeScript中有一个函数可以动态地获取对象的属性值,该属性可以是numberColor类型,如果该属性是number类型,则该函数返回该属性的值,否则返回由该属性创建的数组(在本例中是Color = [R,G,B])。

class Color {
  r: number
  g: number
  b: number
  constructor( r: number, g: number, b: number ) {
    this.r = r;
    this.g = g;
    this.b = b;
  }

  toArray() {
    const array = [0, 0, 0];
    array[0] = this.r;
    array[1] = this.g;
    array[2] = this.b;

    return array;
  }
}

interface MyObject {
   intensity: number, // float number
   color: Color,
                
}

type ObjectProperty = 'intensity'|'color'

const myFunc = (obj: MyObject, property: ObjectProperty): number|number[] => {
   if (typeof obj[property] === 'number') {
      return obj[property] // TS error 2)
   } else {
      return obj[property].toArray() //TS error 1)
   }
}

myFunc抛出TS错误:(一)

TS2339: Property 'toArray' does not exist on type 'number | Color'.   Property 'toArray' does not exist on type 'number'.

和2)

TS2322: Type 'number | Color' is not assignable to type 'number | number[]'.   Type 'Color' is not assignable to type 'number | number[]'.

是否有办法让TS了解在调用toArray()函数之前发生的类型检查以及typeof Color !== number

iqxoj9l9

iqxoj9l91#

通过将obj[property]值赋给常数来消除误差。

const myFunc = (obj: MyObject, property: ObjectProperty): number|number[] => {
  const value = obj[property];
  if (typeof value === 'number') {
    return value
  } else {
    return value.toArray()
  }
}
goqiplq2

goqiplq22#

这种方法似乎不会遇到任何错误...

interface MyObject {
   intensity: number, // float number
   color: {toArray():[number,number,number]}, // Color class represents the color in hex and contains toArray() function
                 // toArray() creates [R,G,B] number array
}

type ObjectProperty = 'intensity'|'color'

const myFunc = (obj: MyObject, property: ObjectProperty): number|number[] => {
  if(property === "color"){
    return obj[property].toArray()
  }
  else{
    return obj[property]
  }
}

相关问题