Is it possible to restrict the count of object properties, say I want to restrict object have only one string propery (with any name), I can do:
{[index: stri
There are many answers to this question on Stackoverflow (including this detailed one), but none of them worked for my situation, which is similar to the one posted here.
I have a function that takes an object. I want it to throw a Compilation Error (Typescript) if the passed object doesn't have exactly one key. e.g.
f({}); // Must error here, as it has less than one key!
f({ x: 5 });
f({ x: 5, y : 6 }); // Must error here, as it has more than one key!
Using the popular UnionToIntersection and IsUnion, I achieved it via the following utility function.
type SingleKey = IsUnion extends true ? never : {} extends T ? never : T;
// From https://stackoverflow.com/a/50375286
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
// From: https://stackoverflow.com/a/53955431
type IsUnion = [T] extends [UnionToIntersection] ? false : true;
// Here we come!
type SingleKey = IsUnion extends true ? never : {} extends T ? never : T;
// Usage:
function f>(obj: SingleKey) {
console.log({ obj });
}
f({}); // errors here!
f({ x: 5 });
f({ x: 5, y : 6 }); // errors here!
Playground Link