Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active July 8, 2020 00:13
Show Gist options
  • Save karol-majewski/343a4e6da0d221f5558438c1ccb2ca4a to your computer and use it in GitHub Desktop.
Save karol-majewski/343a4e6da0d221f5558438c1ccb2ca4a to your computer and use it in GitHub Desktop.
Homogeneous arrays in TypeScript
/**
* @author https://stackoverflow.com/users/2887218/jcalz
* @see https://stackoverflow.com/a/50375286/10325032
*/
type UnionToIntersection<Union> =
(Union extends any
? (argument: Union) => void
: never
) extends (argument: infer Intersection) => void
? Intersection
: never;
type IsSingleton<T> =
[T] extends [UnionToIntersection<T>]
? true
: false
type SingletonOnly<T> =
IsSingleton<T> extends true
? T
: never
interface HomogenousArray<T> extends Array<SingletonOnly<T>> { }
declare function foo<T>(...items: HomogenousArray<T>): T;
foo(1, 2); // ✅ Good!
foo(1, 'foo'); // ⛔️ Compile-time error (expected all members to be of the same type)
@karol-majewski
Copy link
Author

Could have just used:

declare function foo<T>(...items: [T, ...T[]]): T;

foo(1, 2);     // ✅ Good!
foo(1, 'foo'); // ⛔️ Compile-time error (expected all members to be of the same type)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment