Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Understand Node's assert() as a type guard #19622

Closed
jinwoo opened this issue Oct 31, 2017 · 2 comments
Closed

Understand Node's assert() as a type guard #19622

jinwoo opened this issue Oct 31, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@jinwoo
Copy link

jinwoo commented Oct 31, 2017

TypeScript Version: 2.5.3

Code

For code like below:

function getFoo(): Foo {
  const a: Foo|null = null;
  // ...
  // some code that conditionally sets a to a Foo instance.
  // ...
  if (!a) throw new Error('a is not a Foo!');
  return a;
}

, typescript understand that a is non-null when returned from getFoo().

But Node.js has its own assert module, and it is not understood by typescript and we need a type-cast like below:

import * as assert from 'assert';

function getFoo(): Foo {
  const a: Foo|null = null;
  // ...
  // some code that conditionally sets a to a Foo instance.
  // ...
  assert(a);
  return a as Foo;
}

It'd be really great if typescript understands that the non-nullness has been already checked by the assert() call and a is non-null in this case.

@mhegazy
Copy link
Contributor

mhegazy commented Oct 31, 2017

Duplicate of #10470 and #8655

this is a design limitation at the time being. the reachable code analysis happens at an earlier phase, before types are known, and that builds the control flow graph that is used later on. narrowing will use that graph.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Oct 31, 2017
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants