Luis Abreu Luis Abreu - 10 months ago 63
TypeScript Question

typescript 2.0: parameters with default values

Hell guys,

Here's another typescript 2.0 question (with strict null check mode enabled). So, if you define a function which has default values for all parameters:

(name = "Luis", age = 40)=>void

Then all parameters are considered optional, ie, it's as if we have the following signature:

(name?: string, age?: number) => void

Right? Now, what happens when we have this signature:

(name = "Luis", age: number ) => void

According to VS code, that signature is compatible with:

(name: string, age: string) => void

Now, if I activate the strict null check mode, shouldn't the following call produce an error:

doIt(undefined, 30);

It compiles ok, but if I'm not wrong, undefined will only get added automatically to the list of types of optional parameters. I haven't found any references to default initialized parameters.

So, if the previous call is ok, can someone point me to where I can find info about it in the official docs ?



Answer Source

Quick note: You cannot specify defaults in just signatures e.g. the following is an error:

declare var foo: (name = "Luis", age = 40) => void; // ERROR: defaults only allowed in implementation

Continuing the following code:

var foo = (name = "Luis", age: number) => null;
foo(undefined, 123);
foo(null, 123); // ERROR 

Shows that the name is compatible with string or undefined. The tooltip is wrong but the general analysis is correct.

Feel free to raise an issue at