In TypeScript, why does 'T extends never ? never : keyof T` differ from `keyof T'?

Viewed 40

Consider the following definitions:

type OtherKeyOf<T> = T extends never ? never : keyof T;
type OtherKeyOf2<T> = keyof T;

I would expect OtherKeyOf and OtherKeyOf2 to act exactly the same, just as I would expect these two functions to act exactly the same:

const f1 = (t) => false ? false : "some_value";
const f2 = (t) => "some_value";

That isn't what happens, however. Given some dummy types A and B:

interface A {
 aMem: number;
}

interface B {
 bMem: string;
}

I get the following results:

let x: OtherKeyOf<A | B>;  // <= the type of x is `"aMem" | "bMem"`
let y: OtherKeyOf2<A | B>; // <= the type of y is `never`

I find this puzzling. Any help understanding this would be greatly appreciated, thank you!

0 Answers
Related