0

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 ?

Thanks,

Luis

3
  • What is the exact signature of doIt() that you think should cause the compile failure? Commented Oct 26, 2016 at 21:29
  • Hello Dan. well, in my case, doIt would be something like this function doIt(name = "Luis", age: number) { .... }. Commented Oct 27, 2016 at 18:30
  • That explains why there was no compile time error, but I see that @basarat has already explained why :) Commented Oct 28, 2016 at 7:38

1 Answer 1

1

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 https://github.com/Microsoft/TypeScript/issues

Sign up to request clarification or add additional context in comments.

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.