Skip to content

Strict inequality operator (!==) type guard for unknown type #33483

Closed
@kazatsuyu

Description

@kazatsuyu

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
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions