Number Array Type Not Interpreted an Array?

45 views Asked by At
export class ... {
   single: any[] = [];
   multi: any[] = [];

   view: number[] = [700, 400];
   ... <Removed for brevity>
}

Error Msg: Type 'number[]' is not assignable to type '[number, number]'

I'm not really sure what this means. I have a variable which is typed as a number array but when the "view" variable is used in the template it throws the above error. Anyone run into this issue?

The only resolution I have found is to put the array itself--[view]=[700, 400]--in the template. I am a bit baffled by this as it should work.

Thanks.

1

There are 1 answers

0
Daniel Gimenez On BEST ANSWER

The input in your template is expecting a tuple of two numbers, but you've typed view as a number array. The answer is change the typing of view to a tuple.

view: [number, number] = [700, 400];

You can also define your own toTuple method to convert a number array like view to a tuple if necessary.

type Tuple<T, N extends number, R extends T[] = []> = R['length'] extends N ? R : Tuple<T, N, [T, ...R]>;
function toTuple<T, L extends number>(values: T[], length: L): Tuple<T, L> {
  if (values.length < length) {
      throw new Error('invalid values length');
  }
  return values.slice(0, length) as Tuple<T, L>;
}