Control Flow Analysis
Definition:
At each instruction, a variable's type may be narrowed according to the current context.
function cfaSample(x: number|string) {
console.log(x) // : number|string
if (typeof x === 'string') {
console.log(x) // : string
return x
}
return [x] // [number]
} // inferred return type: string|[number]Some expressions (
typeof x === 'string') act as "type guards", narrowing the possible types of a variable inside a context (the if statement);xis narrowed fromnumber|stringtostringinside the if block;xonly can bynumberat the last line, since theifblock returns;The function gets an inferred return type corresponding to an union of all return paths;
Discriminated union
The type
Actionsbelow is called a discriminated union . The propertytypeis used as a tag to filter out which of the union options is valid at the context;At each
caseline below,action.datahas its type narrowed down;
type Actions =
| { type: "create"; data: { name: string } }
| { type: "delete"; data: { id: number } }
| { type: "read"; data: number }
function reducer(action: Actions) {
switch(action.type) {
case 'create':
return createFoo(action.data) // data: {name: string}
case 'delete':
return deleteFoo(action.data) // data: {id: number}
case 'read':
return readFoo(action.data) // data: number
}
}Last updated
Was this helpful?