Last active
July 8, 2020 00:13
-
-
Save karol-majewski/343a4e6da0d221f5558438c1ccb2ca4a 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>(...items: HomogenousArray<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
Could have just used: