Control flow analysis of aliased conditional expressions in TypeScript
Tags: typescript, react
Published: 2021-07-05 12:51:12

An [interesting feature](https://github.com/microsoft/TypeScript/pull/44730) was added to TypeScript recently that will improve the ergonomics of code that relies on type narrowing or discrimination:

TS 4.4 can infer when a variable's type implies something about the type of another.

A simple example given in the PR description:
```typescript
function fn(x: unknown) {
    const isString = typeof x === 'string'
    if (isString) {
        x.length  // Ok
    }
}
```

In TS 4.3.4, [accessing `x.length` is a type error](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMMAKAHgLkeA1mOAdzAEpEBvAKERsQgQGcpEYGBlKAJxjAHNEAvIigBPAA4BTOMETpBAoQHIm3Pouq0YM1Kw6reZKrWOyAdABsJfKAAsA3DQD0jxAFFOnOJ2wB5AEYAVhLQLAyI0sLiEoiKeATE6sYAvpRJQA)...

Even though we know that if (and only if) `isString` is `true`, `x` must be a `string`, the type checker doesn't know that!

This is because `isString` is just a stupid old boolean - it doesn't know or care why it happens to be true or false.

For TS to understand the expression implies something about its inputs, `typeof x === 'string'` has to be inlined inside the if statement (or ternary if you're that way inclined).
```typescript
function fn(x: unknown) {
    if (typeof x === 'string') {
        x.length  // Ok
    }
}
```

This is pretty annoying because we can no longer rearrange our code as we see fit.

We have to choose: do we structure our program to appease the cold, emotionless type checker, or appease nice and cuddly humans using lovely abstractions like names and expression reuse?

We can have our cake and eat it by pulling out the expression into a [type guard predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates), but that's a lot of boilerplate and even bug prone - if our guard predicate and function body fall out of sync, we have an invisible type-checker-defeating bug on our hands!
```typescript
function brokenIsStr(x: unknown): x is string {
  return typeof x !== 'string'
}
```
That's a very dense and dry cake!

At this point TS is looking less like "just JS with types" and more like a verbose subset that's hard to read and write.

This has changed in TS 4.4, as `isString` is [now imbued](https://www.typescriptlang.org/play?ts=4.4.2#code/GYVwdgxgLglg9mABMMAKAHgLkeA1mOAdzAEpEBvAKERsQgQGcpEYGBlKAJxjAHNEAvIigBPAA4BTOMETpBAoQHIm3Pouq0YM1Kw6reZKrWOyAdABsJfKAAsaAenuIA8rg00AvpQ9A) with the implication our brains associate with it - TS understands that iff `isString` is `true`, `x` must be a `string`.

This means we can start decoupling our conditionals from the expressions they depend on; our TS programs start looking a bit more nimble, our cake a little moister!

## Limitations ##

Variables don't encode a history of their every logical implication - it's not magic.

`foo`'s type can only imply something about `bar` when `foo` is `const` and either:
1. the result of a conditional expression about `bar` in the current scope (i.e. `foo` is a boolean)
2. a discriminant property of `bar` (i.e. `bar` is a [discriminated union](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions))

It supports [up to 5 levels of indirection](https://www.typescriptlang.org/play?ts=4.4.2#code/GYVwdgxgLglg9mABMMAKAHgLkeA1mOAdzAEpEBvAKERsQgQGcpEYGBlKAJxjAHNEAvIigBPAA4BTOMETpBAoQHIm3PosrVa9ME2GE4AGQkA3CQBsGAEQkSxgluy49+AHxcOOq3pprbdUAAtOGyNTC2tbeyh9UPMrGzs3Dyc+HzpGZmA4EE5Y8ISooJCTOIjE91ZPZzS-TJhTPPjIoSycxrLEJMqU71p0nWYGGHR2gpb6iVHIrscvGozEACsQJgB5MEmSsw6hbq9OitnnA+T9maq+E73j856NPphgVGAJqbEyKj6+uQB6H8QVNU+gBfNKPVBDEZbJrvChpb6IP44MD4IhgNKgh5PZZrDZ5MofeG0X7-QGpEGUYFAA) before giving up:
```typescript
function fn(x: unknown) {
    const isString = typeof x === 'string'

    const twoLevelsDeep = isString || isString
    const threeLevelsDeep = twoLevelsDeep || isString
    const fourLevelsDeep = threeLevelsDeep || isString
    const fiveLevelsDeep = fourLevelsDeep || isString
    const sixLevelsDeep = fiveLevelsDeep || isString

    const justOneLevelDeep = isString || isString || isString || isString || isString || isString

    if(fiveLevelsDeep) {
        x // string
    }
    if(sixLevelsDeep) {
        x // unknown
    }
    if(justOneLevelDeep) {
        x // string
    }
}
```
and as of yet it doesn't fold away identical expressions.

Whilst an aliased conditional expression on a destructured field will allow for narrowing the original object's type, the flow analysis cannot narrow the type of a destructured sibling.

This coincidentally makes destructuring arguments inside the function signature less useful to the type checker - you may be better off destructuring arguments on the next line.

As an example, a predicate upon `foo` cannot influence the inferred type of `bar` here:
```typescript
function fn({ foo, bar }: Baz) {
  ...
```

But it can influence the type of `baz`:
```typescript
function fn(baz: Baz) {
  const { foo, bar } = baz
  ...
```
This might change in the future, but it's something to bear in mind.

Another important limitation is that narrowing a specific property of an object (as opposed to narrowing the type of the object overall) [requires that property to be readonly](https://github.com/microsoft/TypeScript/pull/44730#issuecomment-868703811), potentially tipping the balance in favour of readonly properties by default.
Despite going out of its way to support mutability, the more advanced TypeScript's analysis gets, the more it encourages functional programming with immutability.

## Downsides ##

There's inevitably some implicit complexity introduced - we'll have to take care to remember when a seemingly innocent boolean is being relied upon by the type checker elsewhere.

Any kind of inference increases coupling between disparate parts of our program - a change over here is more likely to change something over there.
This is a trade off we make all the time; to avoid it entirely requires redundantly and tediously enunciating every single type in your program.

Anyone stuck working with an older version of TS will also have to be slightly more careful when blindly copy pasting from the internet - the weaker inference may render copied code incompatible.

## A Practical Example ##

Let's build a slightly contrived e-commerce website with React - how hard could it be?

Our customers will go through several steps - browsing the catalogue, selecting shipping, then confirming and paying for their order.

Let's represent those steps as React component state using a discriminated union... something like:
```typescript
type ShoppingStep = {
  step: "shopping"
  discountCode?: string
  loggedIn: boolean
}
type SelectShippingStep = Omit<ShoppingStep, "step"> & {
  step: "select-shipping"
  items: Array<Item>
}
type ConfirmOrderStep = Omit<SelectShippingStep, "step"> & {
  step: "confirm-order"
  shippingAddress: Address
}

export function OnlineShop(): JSX.Element {
  const [state, setState] = useState<
    ShoppingStep | SelectShippingStep | ConfirmOrderStep
  >({
    step: "shopping",
    loggedIn: false,
  })

  ...
}
```

With each step represented as a separate component:
```typescript
function Catalogue(props: ShoppingStep): JSX.Element

function ShippingSelect(props: SelectShippingStep): JSX.Element

function ConfirmOrder(
  props: ConfirmOrderStep & {
    freeShipping: boolean;
    children?: ReactNode
  },
): JSX.Element
```

Now let's put it all together by picking the component depending on the step and calculating free shipping eligibility:

```typescript
  const shippingMessage =
    "shippingAddress" in state &&
    checkFreeShippingEligibility(
      state.items,
      state.shippingAddress
    )
      ? `Congrats! Free shipping on ${state.items.length} items!`
      : undefined

  switch (state.step) {
    case "shopping":
      return <Catalogue {...state} />
    case "select-shipping":
      return <ShippingSelect {...state} />
    case "confirm-order":
      return (
        <ConfirmOrder
          {...state}
          freeShipping={
            "shippingAddress" in state &&
            checkFreeShippingEligibility(
              state.items,
              state.shippingAddress
            )
          }
        >
          {shippingMessage ?? "Now pay up!"}
        </ConfirmOrder>
      )
  }
```
Here's the [full code in the playground](https://www.typescriptlang.org/play?jsx=1&ts=4.3.4&strict=true#code/JYWwDg9gTgLgBDAnmApnA3nASighgYxgDkIATNAXzgDMoIQ4AiKPQxgKFElgzgFcAzigDKMXDEo06DZqxgd2SVHACCpUiwEC4AXlVQouRAB4BMKMAB2AcwB8i5GgCSEhnvTs4cS7hAoAXHBmFjaecACOfLiWMMBIgZZ8IABGKFBhYBb4Ad5JqekU7A7KwgAWEGBgVtaiKGC6GGFmdYGMAuWV1RxepMAC+BB8MQDCZCgA-IHB1WEANhDW1iikTpaByRAQs3iW7IVKaMIo24RlwJ02tfV6APIgccZlFVWXEmAANEzNYIy2cABkjS831aQhOMAAtO1zi9rN04HEUCABIEVAYjMYXEj7PtHHBRpZqMAoCAblByFArg07g8juCzhcam9Pm03r8AUCgm9WgNCcSQBDoBT4dDGWoNCgtKj1JoBHsiigAB7ceDUIaEYAQSxwG6WWZWEQdAAUAEpAgApYQADQAdABRbZ+GKc3lmOAAbTM4hQnyEMFE3oAug1BCIxBJjGEvE9GVSAD5wOkoU6lGHVeP4rVEklkilXMK2I0eLzA7lfDqwxjvKNweaLZarQLUXCzITVrwUE1FLyu+Ci2EAWUlAlwS10NbaqbFMuHjAR2q9EgB-xr+FKyYA1gAxFiGtM2B3AazAZLAfVII010vem2I5HtkvXiQ2-vVcWymtdx9ecZwAAGBLWIYMACAAhHAO4oGgr42HAWpwAAJOgi4oLergCDa2w2DApRUHeYF-lecCBEM5BEpYyzdkEADucRrnARooS+bwmpyPa4EI5bPF0-hESwMB8FA2rGMM4gtgsfBoOgNoyShVAAPT2I++AcWgbTHMmkIwXCvHfnA-GCcJDKwkmhAYDJzHegpSklipnGMLy2YCkKaSMLp34GUJDFEV4IlZvyuZpD5JbSbJ4YoIUemPrQUHGdUOjFlFj6Tvu1jvrO85ct6y7Bcp674Nuu5xQe+rHqe56IJeSV6Ux+EPtVJZMdp6VaLlJZftVkVRTZSXIVOg7DqOaDjL+jAkNRcBgEY-BgKBjBdXpxjyQSTmBVAPXtWEhSFOw5D4LMuAsDQ6qxPBoliHWklGpkFQoomFbpixFrWvajooDERR7QdR1qpYGrwcVNQaYQ110GAd2mf6-WPXUZpwJatoOki70wJ9ybfWgv3-dqK0BeSaRVZNYN3bjOb45SbwcolXgxXujLrJs2zRAA3KuqazBKliTNgcgkOQW3VnDCOvcjH27ejh2Yydmramum6QXTsKHmVZ5xJVYT4ai6ImFiIC2A+zUzlKqhGwIgsM1sOzsEAA).

This works, but our shipping message logic is pretty dense, and our free shipping check is duplicated!

Can we do better?

Let's split apart the shipping message logic and reuse the free shipping check:

```typescript
  const freeShipping =
    "shippingAddress" in state &&
    checkFreeShippingEligibility(
      state.items,
      state.shippingAddress
    )

  const shippingMessage =
    freeShipping
      ? `Congrats! Free shipping on ${state.items.length} items!`
      : undefined

  ...

    case "confirm-order":
      return (
        <ConfirmOrder {...state} freeShipping={freeShipping}>
          {shippingMessage ?? "Now pay up!"}
        </ConfirmOrder>
      )
```
Much better! But this line:
```typescript
      ? `Congrats! Free shipping on ${state.items.length} items!`
```
actually fails the type checker in TS 4.3.4 due to `state.items` not necessarily being present: [here's proof](https://www.typescriptlang.org/play?jsx=1#code/JYWwDg9gTgLgBDAnmApnA3nASighgYxgDkIATNAXzgDMoIQ4AiKPQxgKFElgzgFcAzigDK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l1TWYJUsSZsDkEhyDCChq0e57NrenbBq+0afomzVtWXNdULS6pd33Q9j0QEHqNRdETCxEBbBvMybGfSdpQlLRSeRrYdnYIA).

The fix is to duplicate the shipping address check:
```typescript
  const shippingMessage =
    "shippingAddress" in state && freeShipping
      ? `Congrats! Free shipping on ${state.items.length} items!`
      : undefined
```
and now we're paying the price just to satisfy the type checker.

Let's take advantage of the enhanced inference introduced in TS 4.4 to not only deduplicate, but further tidy up our code!

```typescript
  const hasShippingAddress = "shippingAddress" in state

  // `hasShippingAddress` conditional alias
  // allows state to be narrowed to ConfirmOrderStep
  // so `items` and `shippingAddress` are known to be present
  const freeShipping =
    hasShippingAddress &&
    checkFreeShippingEligibility(
      state.items,
      state.shippingAddress
    )

  // state is again narrowed to ConfirmOrderStep because
  // `freeShipping` is an aliased conditional twice removed!
  const shippingMessage = freeShipping
    ? `Congrats! Free shipping on ${state.items.length} items!`
    : undefined

  const {step} = state

  // switching on an (aliased) destructured discriminant property
  switch (step) {
    ...
    case "confirm-order":
      return (
        <ConfirmOrder {...state} freeShipping={freeShipping}>
          {shippingMessage ?? "Now pay up!"}
        </ConfirmOrder>
      )
  }
```
Here's the [full code in 4.4](https://www.typescriptlang.org/play?jsx=1&ts=4.4.2#code/JYWwDg9gTgLgBDAnmApnA3nASighgYxgDkIATNAXzgDMoIQ4AiKPQxgKFElgzgFcAzigDKMXDEo06DZqxgd2SVHACCpUiwEC4AXlVQouRAB4BMKMAB2AcwB8i5GgCSEhnvTs4cS7hAoAXHBmFjaecACOfLiWMMBIgZZ8IABGKFBhYBb4Ad5JqekU7A7KwgAWEGBgVtaiKGC6GGFmdYGMAuWV1RxepMAC+BB8MQDCZCgA-IHB1WEANhDW1iikTpaByRAQs3iW7IVKaMIo24RlwJ02tfV6APIgccZlFVWXEmAANEzNYIy2cABkjS831aQhOMAAtO1zi9rN04HEUCABIEVAYjMYXEj7PtHHBRpZqMAoCAblByFArg07g8juCzhcam9Pm03r8AUCgm9WgNCcSQBDoB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BOE0TEGrhEWtRdETCxEBbDktHGKlVRVOnzuth2dggA) as compared to [the same in 4.3.4](https://www.typescriptlang.org/play?jsx=1&ts=4.3.4#code/JYWwDg9gTgLgBDAnmApnA3nASighgYxgDkIATNAXzgDMoIQ4AiKPQxgKFElgzgFcAzigDKMXDEo06DZqxgd2SVHACCpUiwEC4AXlVQouRAB4BMKMAB2AcwB8i5GgCSEhnvTs4cS7hAoAXHBmFjaecACOfLiWMMBIgZZ8IABGKFBhYBb4Ad5JqekU7A7KwgAWEGBgVtaiKGC6GGFmdYGMAuWV1RxepMAC+BB8MQDCZCgA-IHB1WEANhDW1iikTpaByRAQs3iW7IVKaMIo24RlwJ02tfV6APIgccZlFVWXEmAANEzNYIy2cABkjS831aQhOMAAtO1zi9rN04HEUCABIEVAYjMYXEj7PtHHBRpZqMAoCAblByFArg07g8juCzhcam9Pm03r8AUCgm9WgNCcSQBDoBT4dDGWoNCgtKj1JoBHsiigAB7ceDUIaEYAQSxwG6WWZWEQdAAUAEpAgApYQADQAdABRbZ+GKc3lmOAAbTM4hQnyEMFE3oAug1BCIxBJjGEvE9GVSAD5wOkoU6lGHVeP4rVEklkilXMK2I0eLzA7lfDqwxjvKNweaLZarQLUXCzITVrwUE1FLyu+ClXACBmw8WyhptVNimWSgSMBHar0SbtwAD0y7gAAN+4OJ8Op1p13Beb1YlqW3AW8AB2FV+fZvMAO7aBdoGAQOCpby4AwQe-LBBvgls1Jck0nzLwbwEN910RZED2iUgN1FXcJX3c8WDgABrSwf21V93zQTJJRQGIwl7KQUENNMbF0GstyHaoR2nAF-hrfBSmTDCADEWEoxkHWAaxgGSYB9SQI0a1Lb0bRggR2xLSSJBtJCGL3OV5K7a812fBFtFwaxcCsT9v1-BC8MA-lc1At58PwXBQ00jdaAo+ibAPPpz21C8Bz-I84k1HxZgQe9gGyOAWBACAADdlgAQlIrU3WUmwAFlpz0tA9Cc3jYRrcYNwJaxDBgAQYrgbiKKCHdqjgLU4AAEnQZ9pNcAQbW2GwYFKKgZJi9ca0CIZyCJSxliXMjGreKg9GfJcIOCmA2Oq2rojgI0vKEUgTTgchgj4Qg+BYBDen6Cx7h8Z1MgqNIkCaea2NW74tuLEtbKEctni6fwJLClAYAO7VjGGcQWwWPg0HQG1IefKhl3seTXrQNpjmTSEkrhL75K8Fg-qgAGXJqZHCAwSGlPDFAYbhl7vKYXkgMFECoEYDHMex-7Vu+rxAazCyGeJqGyaoLL8Z0dAhaqmwKEpzGS0a8XrFSrR0rgcY8sYEh7zgMAjH4MAYsYQppc55dzJzBmpZLLsO3ldhyHwWYvzQNVLA1WqgbEOswaNS6wBRRMK3TN4zTgS1bQdJFiJgIpbft9CnZd7V8aTQgvboH3AiT-05auIOQ-tR0I6j5MY8d9UT21E3gIpcSvG932K8sylrMBZ6vDFqjrHWTZtmiABuVjU1mCVLEmbA5BIcgwgoasc+tPPw5Im2i4dmhS-8w92PwLiePx-jBOE0TEGrhEWtRdETCxEBbDktHGKlVRVOnzuth2dggA).

This is loads better - we've got (slightly more) destructuring, lots of named variables and naturally narrowed types, without duplicating type guard expressions.


## Conclusion ##

TS 4.4's flow analysis of aliased conditional expressions starts to deliver - to stretch an analogy - a type checked, moist and light, more JavaScript-y cake.

Our TS code can start looking a bit more like the flexible, human-friendly programs we're used to; we're telling the machine what to do, not the other way around!

Included in the 4.4 release notes is another [write-up of the new feature](https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/#cfa-aliased-conditions) - I recommend giving the whole thing a read as there are a bunch of juicy new features waiting to be tried out!