Generic object rest variables and parameters
TypeScript 3.2 also allows destructuring a rest binding from a generic variable. This is achieved by using the predefined Pick
and Exclude
helper types from lib.d.ts
, and using the generic type in question as well as the names of the other bindings in the destructuring pattern.
function excludeTag<T extends { tag: string }>(obj: T) {
let { tag, ...rest } = obj;
return rest; // Pick<T, Exclude<keyof T, "tag">>
}
const taggedPoint = { x: 10, y: 20, tag: "point" };
const point = excludeTag(taggedPoint); // { x: number, y: number }