Typescript: Narrow type by `typeof value extends Type ? any : never`

Created on 17 Jun 2020  路  4Comments  路  Source: microsoft/TypeScript

Search Terms

Suggestion

Narrow type by typeof value extends Type ? any : never.

Use Cases

declare const x :number | string;
if ( typeof x!=='string' ) { throw TypeError(); }
x;// string

Make inline type narrow code can be util function.

Examples

declare function throwNonString (value :unknown) :typeof value extends string ? void : never;

declare const x :number | string;
throwNonString(x);
x;// string

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
Question

Most helpful comment

The syntax for this is

declare function throwNonString(value: unknown): asserts value is string;

All 4 comments

The syntax for this is

declare function throwNonString(value: unknown): asserts value is string;

@RyanCavanaugh Thank you! And I try to find this syntax in docs again, but I can't find it. Is it forgotten to write in docs?

@fatcerberus Thank you! So it's not in category docs yet... (Only in release notes)

Was this page helpful?
0 / 5 - 0 ratings