Closed
Description
Search Terms
narrow object by property
(unfortunately, this returned way too many results to look through, so sorry if this is a dupe!)
Suggestion
Narrow objects based on checks of their properties.
Use Cases
Some function receives an object as input and then does validation on that object prior to passing it on to some other function, or returning it as a narrowed object.
Examples
declare const apple: { readonly prop: number }
if (apple.prop !== 2) throw new Error()
const appleProp: 2 = apple.prop // no error
// Type 'Apple' is not assignable to type '{ prop: 2; }'.
// Types of property 'prop' are incompatible.
// Type 'number' is not assignable to type '2'.
const banana: {prop:2} = apple
In this example, we can see that the compiler is tracking the narrowed type of apple.prop
because it allows us to assign it to a variable of type 2
. However, when we try to assign the containing object to something that wants a narrowed prop
we get a type error.
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.