Search code examples
angulartypescriptngx-charts

Number Array Type Not Interpreted an Array?


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.


Solution

  • 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>;
    }