Typescript: Strict inequality operator (!==) type guard for `unknown` type

Created on 18 Sep 2019  Β·  1Comment  Β·  Source: microsoft/TypeScript

Search Terms


unknown
strict inequality operator
!==
type guard

Suggestion


unknown type with !== operator should be treated as a type guard.

Use Cases


Using a !== b instead of !(a === b).

Examples

function f1(x: unknown): string | undefined {
  if (!(x === undefined) && typeof x !== 'string') {
    throw new Error();
  }
  return x; // string | undefined
}

function f2(x: unknown): string | undefined {
  if (x !== undefined && typeof x !== 'string') {
    throw new Error();
  }
  return x; // currently x is `unknown`, but it could be `string | undefined`.
}

Checklist

My suggestion meets these guidelines:

  • [ ] 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.
Bug

Most helpful comment

Fix up #33488.

>All comments

Fix up #33488.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fwanicka picture fwanicka  Β·  3Comments

siddjain picture siddjain  Β·  3Comments

remojansen picture remojansen  Β·  3Comments

wmaurer picture wmaurer  Β·  3Comments

kyasbal-1994 picture kyasbal-1994  Β·  3Comments