Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial value for type like [number, number]

Tags:

typescript

I have a field which type is [number, number] and issues with TypeScript compiler (strict set to true) complaining about initial value. I've tried the following:

  1. public sheet: [number, number]; - throws error TS2564: Property 'sheet' has no initializer and is not definitely assigned in the constructor.
  2. public sheet: [number, number] = []; - throws error TS2322: Type 'never[]' is not assignable to type '[number, number]'.
  3. public sheet: [number, number] = [] as [number, number]; the same as above

I know I can create a little monster like public sheet: [number, number] = [] as any as [number, number]; (or assign e.g. [0, 0] what I don't want to do) but I wonder is there a better way to go. Do you have any ideas?

like image 883
Daniel Kucal Avatar asked Oct 17 '25 03:10

Daniel Kucal


1 Answers

This error is comes from the compilerOption strictPropertyInitialization which strict mode enables.

You can use the definite assignment assertion modifier ! to to tell typscript its initialised elsewhere:

public sheet!: [number, number];

like image 53
WayneC Avatar answered Oct 18 '25 17:10

WayneC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!