Skip to content

Narrow generic mapped argumentΒ #57691

Closed as not planned
Closed as not planned
@KnightSlayer

Description

@KnightSlayer

πŸ” Search Terms

"type narrowing for mapped type", "type narrowing for mapped argument", "type narrowing for generic mapped argument"

βœ… Viability Checklist

⭐ Suggestion

I came across a case where the type could obviously be narrowed down. but for some reason typescript doesn't support this. it was a frustrating experience

πŸ“ƒ Motivating Example

Here is code example

type T = 'a' | "b"
type M = {
  a: 1,
  b: 2
}

function f1(a: 'a') {}
function f2(a: 1) {}

function f<TT extends T>(t: TT, p: M[TT]) {
  switch (t) {
    case "a": {
      f1(t);
      f2(p); // Argument of type '1 | 2' is not assignable to parameter of type '1'.  Type '2' is not assignable to type '1'.
      break
    }
  }
}

πŸ’» Use Cases

  1. I want to write more clear code without workarounds
  2. Current approach isn't intuitive
  3. I'm using type casts as workaround in the meantime

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