Skip to content

Instantly share code, notes, and snippets.

@Zalastax
Created October 29, 2018 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zalastax/3f8cc7e3c52b759e057564f351c95e54 to your computer and use it in GitHub Desktop.
Save Zalastax/3f8cc7e3c52b759e057564f351c95e54 to your computer and use it in GitHub Desktop.
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