Skip to content

infer type assertion instead of boolean from "typeof" comparisonsΒ #51835

Closed
@danielrentz

Description

@danielrentz

Suggestion

πŸ” Search Terms

infer type assertion typeof comparison

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
    I am not sure abot this point, it may break some 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

  • The type of expressions typeof x === "<type>" will be inferred as x is <type> instead of boolean (x is Function for "function"; maybe x is object | null for "object"?).
  • Type of expressions x instanceof Class will be inferred as x is Class instead of boolean.

πŸ“ƒ Motivating Example

Doing this would change the return type of custom type assertion functions, which in turn would help filtering arrays for specific type.

before:

const arr1: any[] = [];
const arr2 = arr1.filter(x => typeof x === "string"); // any[]

after:

const arr1: any[] = [];
const arr2 = arr1.filter(x => typeof x === "string"); // string[]

πŸ’» Use Cases

Workaround is adding the type assertion manually:

const arr1: any[] = [];
const arr2 = arr1.filter((x): x is string => typeof x === "string"); // string[]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions