Typescript: Variable still reported as possibly null after nullish coalescing operator

Created on 19 Nov 2019  路  5Comments  路  Source: microsoft/TypeScript

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:

Playground link

Related Issues:

None

Working as Intended

Most helpful comment

We do test this stuff a little before releasing it 馃槈

All 5 comments

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)

Playground

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RyanCavanaugh picture RyanCavanaugh  路  205Comments

blakeembrey picture blakeembrey  路  171Comments

sandersn picture sandersn  路  265Comments

OliverJAsh picture OliverJAsh  路  242Comments

metaweta picture metaweta  路  140Comments