Skip to content

Instantly share code, notes, and snippets.

@cakoose
Last active February 9, 2018 01:52
Show Gist options
  • Save cakoose/d129609840a6acdcd4c3378ba6180fd2 to your computer and use it in GitHub Desktop.
Save cakoose/d129609840a6acdcd4c3378ba6180fd2 to your computer and use it in GitHub Desktop.
Unsoundness with Pick and union subtyping
declare function pick<T,F extends keyof T> (obj: T, fields: F[]): Pick<T, F>;
type User = {
id: number,
email: string,
active: boolean,
};
function ok(u: User) {
const a = pick(u, ['id', 'email']);
console.log(a.id);
console.log(a.active); // <-- compile-time error (good)
}
function bad(u: User) {
const fields: ('id' | 'email' | 'active')[] = ['id', 'email'];
const a = pick(u, fields);
console.log(a.id);
console.log(a.active); // <-- runtime error (bad)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment