Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
4 of 5 tasks
danielrentz opened this issue Dec 9, 2022 · 2 comments
Closed
4 of 5 tasks

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

danielrentz opened this issue Dec 9, 2022 · 2 comments

Comments

@danielrentz
Copy link

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[]
@MartinJohns
Copy link
Contributor

Duplicate of #38390.

@danielrentz
Copy link
Author

Thanks, must have slipped while searching with different terms through multiple pages of matches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants