Skip to content

in operator as type guard / narrowing for partial records and similar objectsΒ #62303

@mfulton26

Description

@mfulton26

πŸ” Search Terms

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

βœ… Viability Checklist

⭐ Suggestion

I'd like to be able to check if a property is in an object and then access that property without needing a type cast.

πŸ“ƒ Motivating Example

given something like:

declare const props: Partial<Record<string, string>>;

I want to be able to access properties in it using in as a type guard:

const answer: string = "answer" in props ? props.answer : "42";

my current workaround is to cast:

const answer: string = "answer" in props ? props.answer as string : "42";

πŸ’» Use Cases

  1. What do you want to use this for? type guards/narrowing
  2. What shortcomings exist with current approaches? I have to cast even though I think TypeScript should already be able to detect that the cast is unnecessary
  3. What workarounds are you using in the meantime? manually cast

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