Skip to content

Instantly share code, notes, and snippets.

@piq9117
Forked from karol-majewski/homogenous-array.ts
Created February 24, 2020 05:22
Show Gist options
  • Save piq9117/a3b50057ba1f378a54477214b17232a5 to your computer and use it in GitHub Desktop.
Save piq9117/a3b50057ba1f378a54477214b17232a5 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>(collection: HomogenousArray<T>): T;
foo([1, 'foo']); // Compile-time error
foo([1, 1]); // ✅
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment