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:
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
In this example, we can see that the compiler is tracking the narrowed type of
apple.propbecause it allows us to assign it to a variable of type2. However, when we try to assign the containing object to something that wants a narrowedpropwe get a type error.Checklist
My suggestion meets these guidelines: