Much more boilerplateness approach than Joe Skeen's, but allows compile time type checks.
And boilerplate util code write just once.. ;)
function usage(t: CortegeOf2<boolean, string>) {
get1(t).toLowerCase(); //ok
// var trash1 = t[2]; //runtime error
// var e0 = get2(t); //compile-time error we cannot get 2nd element cuz t has only 0th and 1st
// var trash2: string = t[1]; //sadly that syntax allows to pass value somewhere, where expected another type
// trash2.toUpperCase(); //runtime error
// var e2: string = get1(t); //but that usage will not allow that pass
}
export interface CortegeOf1<T0> {
0: T0;
}
export interface CortegeOf2<T0, T1> extends CortegeOf1<T0> {
1: T1;
}
export interface CortegeOf3<T0, T1, T2> extends CortegeOf2<T0, T1> {
2: T2;
}
export function get0<T>(cortege: CortegeOf1<T>): T {
return cortege[0];
}
export function get1<T>(cortege: CortegeOf2<any, T>): T {
return cortege[1];
}
export function get2<T>(cortege: CortegeOf3<any, any, T>): T {
return cortege[2];
}
Can be used with arrays:
export function joinTwo<A, B>(a: Promise<A>, b: Promise<B>): Promise<CortegeOf2< A, B >> {
return Promise.all([a, b]);
}
function joinThree<A, B, C>(a: Promise<A>, b: Promise<B>, c: Promise<C>): Promise<CortegeOf3< A, B, C >> {
return Promise.all([a, b, c]);
}