Skip to content

Instantly share code, notes, and snippets.

@rylev
Last active March 17, 2017 13:15
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 rylev/ea6da0ba9a371f56be51624e6c254eda to your computer and use it in GitHub Desktop.
Save rylev/ea6da0ba9a371f56be51624e6c254eda to your computer and use it in GitHub Desktop.
TypeScript
function divide(num1: number | undefined, num2: number | undefined): number | 'no!' | undefined {
if (num1 === undefined || num2 === undefined) { return }
// num1 and num2 now have type number
if (num2 === 0) { return 'no!'}
return num1 / num2
}
type Foo = {
foo: number,
bar: 1 | true
}
type Bar = {
foo: 'hello' | 'world',
bar: 2 | false
}
function example(arg: Foo | Bar): void {
// do something
}
example({foo: 10, bar: true}) // typechecks
example({foo: 'hello', bar: false}) // typechecks
example({foo: 'world', bar: 2}) // typechecks
example({foo: 'nope', bar: false}) // doesn't typecheck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment