Skip to content

keyof returns never when used within type alias #41453

@schickling

Description

@schickling

TypeScript Version: 4.2.0-dev.20201109 (online Playground)

Search Terms:

  • key remapping
  • keyof never

Code

Same code as below as Playground

type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false
type If<Cond extends boolean, Then, Else> = Cond extends true ? Then : Else

type GetKey<
  S extends {},
  V
> = keyof {
  [TP in keyof S as Equal<S[TP], V> extends true ? TP : never]: any
}

type GetKeyWithIf<
  S extends {},
  V
> = keyof {
  [TP in keyof S as If<Equal<S[TP], V>, TP, never>]: any
}


type GetObjWithIf<
  S extends {},
  V
> = {
  [TP in keyof S as If<Equal<S[TP], V>, TP, never>]: any
}

type Task = {
  isDone: boolean
}

type Schema = {
  root: {
    title: string
    task: Task
  }
  Task: Task
}

// correctly returns `"Task"`
type Res1 = GetKey<Schema, Schema['root']['task']>

// incorrectly returns `never`
type Res2 = GetKeyWithIf<Schema, Schema['root']['task']>

// this weirdly works though
type Res3 = keyof GetObjWithIf<Schema, Schema['root']['task']>

Expected behavior:

Res2 should also return "Task".

Actual behavior:

Res2 returns never but Res3 works.

Playground Link:

https://www.typescriptlang.org/play?ts=4.2.0-dev.20201109#code/C4TwDgpgBAogjgVwIYBsA8BBANFAQgPigF4oAKNAFX1IEpjCKoIAPYCAOwBMBnKDKAPxQAjFABcUAEx0WbLr3JVa9KI1kceeQSPFS6Q4ACcE0CQDNU3CAChQkKAEkzaAMIB7Lk1YbeAIzduKBBI7DgUABYcODAoVoQk7p7q8lBGJtoRHLoxVta24NAA4hDAANIQIGjWUFAAyl5ymgDeAL5Y1VAAatbxUADWFW5mUE0dANoUAApQAJbs-YPD9Ui88MjotROTALo4nYTJmmnQQlO67BAAbhCG2xIhINYteXZFJeUgAOozwOFOVTV6odeK12jVur0BiAhiNxmc5gtoUsoCtHM41qg0JsprsuvgwpMcBdroZ8HcUexHs8XgUoMVgAB5XwAK2+v3+HSB3hSoI6EOIsJqW1m8yhMOWvH+GI2W1x+wJRKuNzJ90pTxp9goKz6AtGNRm3AAIh4IBJ-IFgux1fl7LUAMaRAC2SF1HUMAWAEj1NVSPyCEm4RjmAHMOjVgNqJFruH0Os8atG+lHtdaAPSpqB2tyGQwQO3AFAgKC54AIQzsXgAAwARInq5WbdAAEoQbiiEj0j5Yh0QZ04e1OpBjADk7rcwGH2xHEZjk-weXTIqzObzBaLJbLFagleJNwbrygLe4kgFnYqbL+zgHvaQ-Z7zpHY4nU+HM76c4XGd+BqgAHcIDMhicIWf7Zn0vC-G4CDBuEjaHq2ADMApisM9JMqyPyXt2g53oOj4epO07anOQA

Related Issues:

PS: Dear issue triage folks, I'm not sure whether I hit the nail on its head in the issue title, so please feel free to adjust it to be more accurate/descriptive.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions