上QQ阅读APP看书,第一时间看更新
Union types
The basic definitions of the previous section may be enough for plenty of code, but as you start working with more complex problems, you'll need some more advanced Flow features, and you may want to define types separately so that you can reuse them elsewhere. Due to this, in this and the following sections, we'll look at more advanced types.
In JS, it's common that a variable may have, at different times, different data types. For that situation, you can use union types:
// Source file: src/types_advanced.js
let flag: number | boolean;
flag = true; // OK
flag = 1; // also OK
flag = "1"; // error: wrong type
let traffic: "red" | "amber" | "green"; // traffic is implicitly string
traffic = "yellow"; // error: not allowed
type numberOrString = number | string;
function addTwo(x: numberOrString, y: numberOrString) {
return x + y;
}
// continues...
For some occasions in which you have objects that have different properties depending on some internal value, you can also use disjoint unions; see https://flow.org/en/docs/types/unions/.