Skip to content

Instantly share code, notes, and snippets.

@caasi
Created February 4, 2020 20:40
Show Gist options
  • Select an option

  • Save caasi/93b439e77984c41c0a9fc485a1efe093 to your computer and use it in GitHub Desktop.

Select an option

Save caasi/93b439e77984c41c0a9fc485a1efe093 to your computer and use it in GitHub Desktop.
// Some helper types from:
// https://dev.to/miracleblue/how-2-typescript-get-the-last-item-type-from-a-tuple-of-types-3fh3
// Borrowed from SimplyTyped:
type Prev<T extends number> = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62][T];
// Actual, legit sorcery
// Borrowed from pelotom/hkts:
type GetLength<original extends any[]> = original extends { length: infer L } ? L : never;
type GetLast<original extends any[]> = original[Prev<GetLength<original>>];
type Without<T, U> = T extends U ? never : T;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type TupleToUnion<A extends any[]> = A extends { [n: number]: infer T } ? T extends object ? T : never : never;
function foobar<T extends any[]>(...args: T): UnionToIntersection<Without<TupleToUnion<T>, GetLast<T>>> {
let obj = {};
for(let a of args) {
if (typeof a === 'function') continue;
obj = Object.assign(obj, a);
}
return obj as UnionToIntersection<Without<TupleToUnion<T>, GetLast<T>>>;
}
const foo = foobar({ foo: 1 }, { bar: 'bar' }, () => null); // { foo: number } & { bar: string }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment