0
type a = { [K in keyof { "foo" }]: { foo: "bar" } extends { K } ? true : false }["foo"];
type b = { foo: "bar" } extends { "foo" } ? true : false;

a and b should both be type true according to my understanding, but a turns out to be false.
Could anyone help explain the reason? Or maybe it's a bug in TypeScript?
Note: tested under TypeScript 4.4.4

1 Answer 1

0

Well, I've reported this problem as an issue in TypeScript's official repository, and here's the reply from RyanCavanaugh, which solves this problem.

type a = { foo: "bar" } extends { "foo" } ? true : false;
type b = { [K in keyof { "foo" }]: { foo: "bar" } extends { K } ? true : false }["foo"];

The type being resolved here (annotated for additional clarity) is

{ foo: "bar" } extends { K: any } ? true : false

K in this position is a property name, not a reference to the key type. You could equally have written

type a = { foo: "bar" } extends { "foo" } ? true : false;
type b = { [K in keyof { "foo" }]: { foo: "bar" } extends { QQQ } ? true : false }["foo"];

Which is clearly correctly false

This is true as expected:

type b = { [K in keyof { "foo": any }]: ({ foo: "bar" } extends Record<K, unknown> ? true : false) }["foo"];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.