Skip to content

Discriminate the type of a value that is dynamically accessed, based on a type guardΒ #49632

@JesusTheHun

Description

@JesusTheHun

Suggestion

πŸ” Search Terms

type modifier, infer optional property

βœ… Viability 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, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

In the case of a type that is either T or T | undefined, typescript should be able to select the type when a type guard is applied instead of enforcing T.

πŸ“ƒ Motivating Example

A more complex scenario can be explored in the playground.

type SomeType = {
  a: string;
  b?: string;
  c?: number;
}

type StringsOfSomeType = "a" | "b"; // typically this is dynamically defined

const obj: SomeType = { a: "foo" };
const props: Array<StringsOfSomeType> = ["a", "b"];
const p = props[1];

if (obj[p] === undefined) {
  obj[p] = undefined; // I suggest this should be possible because the condition allow us to determine that we are in a case where the value type is `string | undefined`
}

πŸ’» Use Cases

Applying transformations in middleware functions.
Currently I have found no workaround.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions