Last active
February 9, 2018 01:52
-
-
Save cakoose/d129609840a6acdcd4c3378ba6180fd2 to your computer and use it in GitHub Desktop.
Unsoundness with Pick and union subtyping
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
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