Closed
Description
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 asx is <type>
instead ofboolean
(x is Function
for "function"; maybex is object | null
for "object"?). - Type of expressions
x instanceof Class
will be inferred asx is Class
instead ofboolean
.
π 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
Labels
No labels