3

In

type GetTruthyKeys<T extends object> = {
    [key in keyof T]: T[key] extends false ? never : key
}[keyof T];

the [keyof T] part seems to be extracting keys from the mapped type, but why does it work?

If

{
    [key in keyof T]: T[key] extends false ? never : key
}

part simply maps the object by changing the false type with never and other types with key value, so that this

{
    first: true;
    second: false;
    third: string;
}

going to be mapped to this

{
    first: "first";
    second: never;
    third: "third";
}

doesn't it mean that to get keys of the latter type we need to put keyof in front of the mapping? So it would look like this

type GetTruthyKeys<T extends object> = keyof {
    [key in keyof T]: T[key] extends false ? never : key
}; // it returns union of all three keys, even with one that has type of false

So how and why the [keyof T] works in this case?

Chaz Ashley
  • 389
  • 1
  • 15
  • 1
    It's a [lookup type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types) which extracts the (union of) property type(s) at that (union of) key(s). – jcalz Sep 23 '20 at 16:58
  • 1
    `{first: "first"; second: never; third: "third"}["first" | "second" | "third"]}` evaluates to `"first" | never | "third"` which is just `"first" | "third"` – jcalz Sep 23 '20 at 17:02

0 Answers0