Last active
March 17, 2017 13:15
-
-
Save rylev/ea6da0ba9a371f56be51624e6c254eda to your computer and use it in GitHub Desktop.
TypeScript
This file contains hidden or 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
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 | |
} |
This file contains hidden or 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
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