-
-
Save Zalastax/3f8cc7e3c52b759e057564f351c95e54 to your computer and use it in GitHub Desktop.
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
interface HasSsn { | |
ssn: string | |
} | |
interface Credit { | |
income: number | |
age: number | |
} | |
interface HasSsnAndCredit { | |
ssn: string | |
credit: Credit | |
} | |
interface HasNoCredit { | |
credit: undefined | |
} | |
function hasSsn(v: any): v is HasSsn { | |
return v.ssn != null | |
} | |
// This is what we need to make it type safe and typo safe | |
function creditLookup<P>(person: P | P & HasSsn): P & HasNoCredit | P & HasSsnAndCredit { | |
if (hasSsn(person)) { | |
return Object.assign({ credit: { income: 2000, age: 42 } }, person) | |
} | |
return Object.assign({ credit: undefined }, person) | |
} | |
// This would work as well but we are not safe for putting in bad credit | |
function creditLookup2<P>(person: P | P & HasSsn): P | P & HasSsnAndCredit { | |
if (hasSsn(person)) { | |
// the next line is type correct :o | |
// return Object.assign({ credit: { inkomst: 2000, age: 42 } }, person) | |
return Object.assign({ credit: { income: 2000, age: 42 } }, person) | |
} | |
return person | |
} | |
const data = [ | |
{ ssn: "1234" }, | |
{name: "foo"}, | |
{ssn: "1234", name: "foo"}] | |
console.log(data.map(creditLookup)) | |
console.log(data.map(creditLookup2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment