Static Control Flow Analysis in TypeScript

What is Static Control Flow Analysis in TypeScript?

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)
  }
}

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.