My strong guess is that purpose of KnownKeys
is to get all explicit or "known" keys from a hybrid type with both hard-coded properties and index signature (see this post for more info and type credit).
KnownKeys
has no effect on a type without index signature:
type T11 = KnownKeys<{ test: 34, 23: 'test'}> // "test" | 23
type T12 = keyof { test: 34, 23: 'test'} // same as above
But with a hybrid type, there is a difference:
type T21 = KnownKeys<{ [K: string]: number, foo: number }> // here we can extract "foo"
type T22 = keyof { [K: string]: number, foo: number } // string | number, this is not so useful...
It works, because a mapped type returns both the index signature and explicit properties:
type T3 = {[K in keyof { [K: string]: number, foo: number }]: number}
// { [x: string]: number; foo: number; } returns signature and "foo" property
So we can assign a never
value to the signature part [x: string]: number
with the type expression string extends K ? never : number extends K ? never : K
. And just filter out all properties with never
value by extends { [_ in keyof T]: infer U } ? U : never;
.
Code