You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
strictNullChecks and nullable parameters with defaults #14236
It seems that TS 2.2.1 changed the behavior of nullable parameters (NOTE: null specifically, not undefined) with defaults when compiling with --strictNullChecks. Was this change intentional? It's a breaking change.
I imagine this is a consequence of #12033, but AFAICT affecting null was likely an unintentional side effect.
Code
typeOptionalString=string|null|undefined;functionhasDefault(val: OptionalString=""){// TS 2.1.6, type of val is OptionalString// TS 2.2.1, type of val is string}// TS 2.1.6, next line compiled fine// TS 2.2.1, error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'.hasDefault(null);
Expected behavior:
Type of val to be OptionalString (or string | null) and for null to be an accepted parameter.
Actual behavior:
Type of val is string and null is not accepted as an argument to the function.
That's not the same case. In your example the parameter is not declared to accept null at all. Try this:
functionf(x: string|null=""){returnx.length;// Error: Object is possibly `null`}f("abc");// 3f(undefined);// 0f(null);
That's how it should work. null should be accepted, but the function has to check for and handle it. However, note the different behavior between these two examples:
typeT=string|null;functionf(x: T=""){returnx.length;// Error here: `x` may be `null`}f(null);
Compare to this:
typeT=string|null|undefined;functionf(x: T=""){returnx.length;}f(null);// Error here: `null` is not assignable to parameter of type `string | undefined`
The first issue can be handled correctly, by checking for null within the function. The latter issue cannot be handled at all, because it incorrectly removes null from the type.
Reacted by Jessica Franco, Leonardo Ascione and Chris Harrison
Activity
andy-hanson commentedon Feb 23, 2017
Try it out in a JavaScript console.
If you pass in
nulland it expects astring, you'll have runtime errors.jaredru commentedon Feb 23, 2017
That's not the same case. In your example the parameter is not declared to accept
nullat all. Try this:That's how it should work.
nullshould be accepted, but the function has to check for and handle it. However, note the different behavior between these two examples:Compare to this:
The first issue can be handled correctly, by checking for
nullwithin the function. The latter issue cannot be handled at all, because it incorrectly removesnullfrom the type.ahejlsberg commentedon Mar 7, 2017
Nathan Shively-Sanders (@sandersn) Ryan Cavanaugh (@RyanCavanaugh) Make sure #14498 also fixes this one.