0

Since updating Typescript to 3.x I can not compile this class anymore:

class MyClass<T>{
    private myMethods: [(val: T) => void] = [] as [(val: T) => void];
}

More specific, it is [] as [(val: T) => void] that triggers the error and the compiler message is:

Error:(7, 47) TS2352: Type '[]' cannot be converted to type '[(val: T) => void]'.
  Property '0' is missing in type '[]'. 

It DO work in Typescript 2.9.2 though!

So what is the problem here and how do I solve it?

Rox
  • 2,647
  • 15
  • 50
  • 85
  • Is [this question](https://stackoverflow.com/questions/44447730/property-0-is-missing-in-type) helpful? – raina77ow Aug 29 '18 at 15:28
  • Probably a breaking change, although I can't find any documentation in 3.0 about it. Length was added to tuples a while ago so it's probably not because of that. Tuples were worked on in 3.0 so that might have something to do with it. The simplest solution is to asset to `any` or use `[null]` instead as that would be a valid value for your tuple with a single element – Titian Cernicova-Dragomir Aug 29 '18 at 15:49

2 Answers2

1

This is due to tuple length enforcement in TypeScript 3.0 which forces signature [T] to have one element in the array of type T.

The only solution is to make an element type optional as follow.

class MyClass<T>{
    private myMethods: [((val: T) => void)?] = [] as [((val: T) => void)?];
}
Akash Kava
  • 39,066
  • 20
  • 121
  • 167
1

If myMethods is not a tuple but an array (as the name suggests,) you can just do

class MyClass<T>{
    private myMethods: Array<(val: T) => void> = [];
}
Oblosys
  • 14,468
  • 3
  • 30
  • 38