-
-
Save swennemans/2545c9136d2a7b7a3581cc3f715c8631 to your computer and use it in GitHub Desktop.
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
// @flow | |
function getOptions() { | |
return { num: 42, str: "val" }; | |
// ^ Type of this return is inferred without type annotation. | |
} | |
/*:: | |
// ^ Comments like this are part of Flow's Comment Syntax. | |
// They allow you to include any additional syntax and Flow will parse it | |
// like you haven't commented it out. Allowing you to write Flow code without | |
// breaking JavaScript at runtime. | |
// Despite the syntax highlighting this is still in a comment so it won't | |
// execute. | |
var __options__ = getOptions(); | |
// ^ Flow will assign the inferred return type to the __options__ | |
// value. | |
// What we've just done is interesting because we've extracted a type from | |
// an arbitrary expression. Normal type annotations cannot do this (hopefully | |
// in the future they will be able to). | |
// Now we can create a type alias with our extracted inferred type. | |
type Options = typeof __options__; | |
// ^ typeof extracts the type from the __options__ value. | |
*/ | |
// Now we can use the Options type alias as a type annotation. Our code is type | |
// checked: | |
var options /*: Options */ = { | |
num: "hi", // error: string should be number | |
str: 42 // error: number should be string | |
}; | |
// Note that all of the above is valid JavaScript syntax. We've just been using | |
// comments so this is what JavaScript sees: | |
function getOptions() { | |
return { num: 42, str: "val" }; | |
} | |
var options = { | |
num: "hi", | |
str: 42 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment