I am confused by the keyof
operator when applied to an empty object. Example code:
const o = {};
const k : Array<keyof typeof o> = [];
// k has type never[]
Why is the type never
? I thought never is the return type of functions that never return. Should the type not be any[]
instead?
When changing the object like this, the type makes sense:
const o = {a: 1, b: 2};
const k : Array<keyof typeof o> = [];
// k has the type ("a" | "b")[]
I found this behaviour when implementing a function that returns the typed keys of an object:
function getKeys(o: object) {
return Object.keys(o) as Array<keyof typeof o>;
}
The function has the return type never[]
but should actually have (keyof typeof o)[]
if I am correct