My TypeScript function dynamically retrieves a value of an object's property. The property can be either a number
or a Color
. If it's a number
, the function returns the property value. Otherwise, it returns an array created from the Color
properties (in this case, [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]
} else {
return obj[property].toArray()
}
}
myFunc
is throwing TS errors:
TS2339: Property 'toArray' does not exist on type 'number | Color'. Property 'toArray' does not exist on type 'number'.
and
TS2322: Type 'number | Color' is not assignable to type 'number | number[]'. Type 'Color' is not assignable to type 'number | number[]'.
Is there a way to help TypeScript understand the type check that occurs before calling the toArray()
function and the fact that typeof Color !== number
?