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?

2
  • Is this question helpful? Commented Aug 29, 2018 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 Commented Aug 29, 2018 at 15:49

2 Answers 2

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)?];
}
Sign up to request clarification or add additional context in comments.

Comments

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> = [];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.