Skip to content

Suggestion: check narrowed type in user-defined type guards #29980

Closed as not planned
@OliverJAsh

Description

@OliverJAsh

Search Terms

validate type check user defined guard return narrow

Suggestion

const checkIsNumber = (value: unknown): value is number => typeof value === "string";

This function is invalid because the type specified in the return type (number) does not match the reality at runtime (string). However, TS does not currently throw a type error.

Could TypeScript type check user-defined type guards? Specifically it should check the narrowed type of value in the function body (after all guards) matches the explicit return type.

const checkIsNumber = (value: unknown): value is number =>
  typeof value === "string" &&
  (() => {
    // TS knows here that the type is narrowed to `string`.
    // This does not match the explicit return type of this user-defined type guard (`number`).
    // Therefore, TS could/should error?
    value;

    return typeof value === "string";
  })();

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

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions