Skip to content

The evaluation of the Keyof Type Operator produces different results to the Pick built-in tool.Β #48173

Closed
@someBrown

Description

@someBrown

Bug Report

πŸ”Ž Search Terms

Pick

πŸ•— Version & Regression Information

v4.5.4

⏯ Playground Link

Link

πŸ’» Code

interface User {
  name?: string
  age?: number
  address?: string
}

type Foo<T, U = keyof T> = {
  [P in Extract<U, keyof T>]: T[P]
}

type Bar<T,U=keyof T> = Required<Pick<T, Extract<U, keyof T>>>

type Res = Foo<User, 'name'>     //name: string | undefined;
type Res2 = Bar<User, 'name'>   //name: string
// We can quickly address your report if:
//  - The code sample is short. Nearly all TypeScript bugs can be demonstrated in 20-30 lines of code!
//  - It doesn't use external libraries. These are often issues with the type definitions rather than TypeScript bugs.
//  - The incorrectness of the behavior is readily apparent from reading the sample.
// Reports are slower to investigate if:
//  - We have to pare too much extraneous code.
//  - We have to clone a large repo and validate that the problem isn't elsewhere.
//  - The sample is confusing or doesn't clearly demonstrate what's wrong.

πŸ™ Actual behavior

type Res = Foo<User, 'name'>     //name: string | undefined;

The value evaluated for the name contains undefined

πŸ™‚ Expected behavior

type Foo<T, U = keyof T> = {
  [P in Extract<U, keyof T>]: T[P]
}

[P in Extract<U, keyof T>]: T[P] should not return undefined because Extract only narrows down the range of the keys

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions