It seems that the purpose of KnownKeys
is to extract all explicit or "known" keys from a hybrid type containing both hard-coded properties and an index signature (check out this post for more details and credit).
KnownKeys
does not affect types without an index signature:
type T11 = KnownKeys<{ test: 34, 23: 'test'}> // "test" | 23
type T12 = keyof { test: 34, 23: 'test'} // same as above
However, when dealing with a hybrid type, there is a distinction:
type T21 = KnownKeys<{ [K: string]: number, foo: number }> // allows extraction of "foo"
type T22 = keyof { [K: string]: number, foo: number } // string | number, which may not be very useful...
This functionality 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; } includes the signature and the "foo" property
We can assign a value of never
to the signature part [x: string]: number
using the type expression
string extends K ? never : number extends K ? never : K
. Then filter out all properties with a
never
value by
extends { [_ in keyof T]: infer U } ? U : never;
.
Code