You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If a union contains multiple non-nullish values, I expect it to be ok to access the property. This would then yield the type defined by one of the union members, or undefined.
π Motivating Example
interfacePerson{hands: string[]}interfaceCat{paws: string[]}declareconstmaybePerson: Person|undefinedconsthands1=maybePerson?.hands// ^^^^^^ This is `string[] | undefined`declareconstcreature: Cat|Personconsthands2=creature.hands// ^^^^^^ I expect this to be `string[] | undefined` too// This often leads to awkward constructs with `in` checksif('hands'increature){creature.hands.map(hand=>hand)}// where at runtime optional chaining would be fine.creature.hands?.map(hand=>hand)
interfaceMonke{hands: number}interfaceCat{paws: number;}constmutant={paws: 4,hands: "now with opposable thumbs"};constanimal: Monke|Cat=mutant;// ok, extra property allowedconsole.log(animal.hands)// proposed: number | undefined, but actually a string!
A 'key' in object check will work here, but that's an intentional tradeoff because you have to opt in to unsoundness.
π Search Terms
union optional property access
β Viability Checklist
β Suggestion
If a union contains multiple non-nullish values, I expect it to be ok to access the property. This would then yield the type defined by one of the union members, or undefined.
π Motivating Example
π» Use Cases
I often find myself writing:
Or even:
Or worse, nested constructs:
This is purely to make TypeScript happy. The following is just as safe:
The text was updated successfully, but these errors were encountered: