Skip to content

Optional chaining with non null operator is unsafe, because it could throw an exception #36031

Closed
@macabeus

Description

@macabeus

TypeScript Version: 3.7.2

Search Terms: optional chaining, non null operator

Code

This input

a?.b!.c

will compile to

((_a = a) === null || _a === void 0 ? void 0 : _a.b).c;

But it's unsafe, because if a is null or undefined, will throw an exception:

   ((_a = a) === null || _a === void 0 ? void 0 : _a.b).c
=> ((_a = null) === null || _a === void 0 ? void 0 : _a.b).c
=> (null === null || _a === void 0 ? void 0 : _a.b).c
=> (true ? void 0 : _a.b).c
=> undefined.c

IMO we should not raise this exception.

Expected behavior:

Would be better to compile to

(_a = a) === null || _a === void 0 ? void 0 : _a.b.c;

So a could be null or undefined and it'll not raise an exception anymore.

Playground Link: Playground

Related Issues: There was a lot of discussion here, but was more focused in the type system, not about the code output that raise wrongly an exception.

Also this bug was reported in Babel and already there is a PR to fix that in Babel:

In this issue I'm saying only about the output, not about the type system.

Metadata

Metadata

Assignees

Labels

Breaking ChangeWould introduce errors in existing codeCommittedThe team has roadmapped this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions