Skip to content

Allow property if at least one union item itΒ #56752

Closed as not planned
Closed as not planned
@remcohaszing

Description

@remcohaszing

πŸ” 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

interface Person {
  hands: string[]
}

interface Cat {
  paws: string[]
}

declare const maybePerson: Person | undefined

const hands1 = maybePerson?.hands
//    ^^^^^^ This is `string[] | undefined`

declare const creature: Cat | Person

const hands2 = creature.hands
//    ^^^^^^ I expect this to be `string[] | undefined` too

// This often leads to awkward constructs with `in` checks
if('hands' in creature) {
  creature.hands.map(hand => hand)
}

// where at runtime optional chaining would be fine.
creature.hands?.map(hand => hand)

πŸ’» Use Cases

I often find myself writing:

if ('key' in object) {
  doSomething(object.key)
}

Or even:

if (object && 'key' in object) {
  doSomething(object.key)
}

Or worse, nested constructs:

if (object && 'key' in object && typeof object.key === 'object' && object.key != null || 'nested' in object.key) {
  doSomething(object.key.nested)
}

This is purely to make TypeScript happy. The following is just as safe:

if(object?.key?.nested) {
  doSomething(object.key.nested)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions