TypeScript Version: 3.8.0-dev.20191119
Search Terms:
nullish
Code
const takesAString = (s: string) => s
let maybeString: string | null
const result = maybeString ?? takesAString(maybeString)
Expected behavior:
Since takesAString will never be executed when maybeString === null due to the nullish coalescing operator this code should be valid.
Actual behavior:
Passing maybeString to the function results in the error:
error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.
This only happens when strictNullChecks: true, but it should be fine either way.
Playground Link:
Related Issues:
None
The RHS of ?? is evaluated when the LHS is nullish, not when it isn't. Nullish coalescing means "Use the value on left if it's not nullish, otherwise substitute this other thing on the right."
This slightly modified version of your example prints null if you actually run it:
const takesAString = (s: string) => console.log(s);
let maybeString: string | null = null;
const result = maybeString ?? takesAString(maybeString)
Did you actually run my example? Open the console and press Ctrl+Enter - it prints null, which means null was passed to takesAString(). It seems like you're misunderstanding what the ?? operator actually does.
Nullish coalescing isn't "If this is defined, use the thing on the right". It's "If this is defined, use it, otherwise use the thing on the right." The former would be #34847.
@fatcerberus I deleted my comment as soon as I posted it. I somehow confused this with ?.. This is not an issue. Thanks for the quick reply!
We do test this stuff a little before releasing it 馃槈
But so many edge cases, maybe you missed one... 馃槣
Thanks for your hard work on TypeScript and these additions in 3.7!
Most helpful comment
We do test this stuff a little before releasing it 馃槈