-
-
Save piq9117/6d5f91a5510b89cfa010469e2d54330c to your computer and use it in GitHub Desktop.
Homogeneous arrays in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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