Skip to content

Instantly share code, notes, and snippets.

@xiel
Created March 2, 2019 16:51
Show Gist options
  • Save xiel/46d9e67edc93a6e470bf737802657a05 to your computer and use it in GitHub Desktop.
Save xiel/46d9e67edc93a6e470bf737802657a05 to your computer and use it in GitHub Desktop.
Typescript | Conditional Types
interface foo {
foo1: string
foo2: string
blubb: string
}
interface bar {
bar1: number
bar2: number
blubb: number
}
function that(accepts: bar | foo) {
if ('foo1' in accepts) {
console.log(accepts.blubb)
onlyFoo(accepts)
return accepts.foo1 + accepts.foo2
} else {
console.log(accepts.blubb)
return accepts.bar1 + accepts.bar2
}
}
function onlyFoo(foo: foo) {
console.log(foo.foo1)
}
that({
foo1: "foo1",
foo2: "foo2",
blubb: "blubb in foo"
})
that({
bar1: 2,
bar2: 1,
blubb: 0xb1cb
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment