Home > database >  TypeScript doesn't recognize class member type
TypeScript doesn't recognize class member type

Time:12-15

I have this class:

export class Colors {
constructor(
private domain: string[] = ['#F44336', '#FDB856', '#59CA08', '#08821C'],
private range: [number | string, number | string] = [-100, 100],
private delimiters: number[] | string[] = [50, 62.5, 75]
) {
 if (typeof range[0] === 'string') {
  range[0] = parseInt(range[0]);
 }

 if (typeof range[1] === 'string') {
  range[1] = parseInt(range[1]);
 }
}

public transpose100(val: number): number {
 const maxRange = this.range[1] - this.range[0];
 return ((val - this.range[0]) / maxRange) * 100;
 }
}

Contructor ensures the range to be the type of [number, number] but the compiler still highlights his usage inside the transpose100 function, telling me the range is of type [number | string, number | string]

CodePudding user response:

A better way to implement what you're looking for is to use constructor overloading.

CodePudding user response:

I solved declaring the range property before his initialization:

export class Colors {
private range: [number, number] = [-100, 100];

constructor(
private domain: string[] = ['#F44336', '#FDB856', '#59CA08', '#08821C'],
range: [number | string, number | string] = [-100, 100],
private delimiters: number[] | string[] = [50, 62.5, 75]
) {
if (typeof range[0] === 'string') {
  range[0] = parseInt(range[0]);
}

if (typeof range[1] === 'string') {
  range[1] = parseInt(range[1]);
}

this.range[0] = range[0];
this.range[1] = range[1];
}
  • Related