I want to infer the number of keys of an object.
For an array, this works:
type LengthArray<T extends readonly any[]> = T["length"];
type Length = LengthArray<["ryan", 1, true, 90]>;
// Length is 4 :)
I'm trying to do this from an object:
type LengthObject<T> = Array<keyof T>["length"];
type Length = LengthObject<{ name: string; age: number }>;
// Length is number :(
I would need to know that in the above interface, the number of properties would be exactly 2, not "number".
At the end of the day, what I would most like to know is whether the object has no properties:
type LengthObject<T> = <?>
function infer<T>(o: T): LengthObject<T> extends 0 ? number : string {
// ...
}
const r1 = infer({}); // r1 is number;
const r2 = infer({ name: "ryan" }); // r2 is string;