Static Control Flow Analysis
Unreachable Code
TypeScript is not all about static type checking. It also statically checks code from other perspectives.
For example, TypeScript informs about logical inconsistencies in control flow resulting in unreachable code.
if (true) {
console.log('foo')
} else {
console.log('bar') // TS: Unreachable code detected.
}
The flag allowUnreachableCode
can be set to true
in tsconfig.json
to disallow unreachable code.
Always True or False Conditions
In some cases, TypeScript can indicate that a condition is always true
or always false
.
type Responses = '200' | '201'
const logResponse = (response: Responses) => {
if (response !== '200' || response !== '201') { // TS: This condition will always return 'true' since the types '200' and '201' have no overlap.
console.log(response)
}
}
const logResponseButDifferent = (response: Responses) => {
if (response === 200 && response === 201) { // TS: This condition will always return 'false' since the types '200' and '201' have no overlap.
console.log(response)
}
}