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
Because this question has been marked as a duplicate of this one, let me answer here.
Check if a type is a union
/**
* @see https://stackoverflow.com/questions/53953814/typescript-check-if-a-type-is-a-union/53955431
*/
type IsSingleton =
[T] extends [UnionToIntersection]
? true
: false
/**
* @author https://stackoverflow.com/users/2887218/jcalz
* @see https://stackoverflow.com/a/50375286/10325032
*/
type UnionToIntersection =
(Union extends any
? (argument: Union) => void
: never
) extends (argument: infer Intersection) => void
? Intersection
: never;
Allow only singleton types
type SingletonOnly =
IsSingleton extends true
? T
: never
Restrict a function to accept only a singleton type
declare function foo(s: SingletonOnly): void
declare const singleton: 'foo';
foo(singleton);
declare const union: "foo" | "bar";
foo(union); // Compile-time error
TypeScript Playground