# Convert your Typescript codebase to No Unchecked Indexed Access

Learn how to improve type safety in your TypeScript codebase by enabling the 'noUncheckedIndexedAccess' setting. This guide provides practical steps and a script to automate the process, making it manageable even in large codebases.

Written by [Greg Dingle](#)

Published May 2023 - 5 min read

[![A typescript code displayed on a screen](https://www.flux.ai/p/assets/blogs/nouncheckedindexed/main.webp)](#)

### Introduction

Flux.ai was started around 3 years ago in TypeScript with the [default compiler settings](https://www.typescriptlang.org/tsconfig). If we could go back in time, there is one setting we would surely change: [noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess). By default, this setting is false. [Many people believe](https://github.com/microsoft/TypeScript/issues/49169) it should be true.

### The flag

What does noUncheckedIndexedAccess do? By default, TypeScript assumes any array element or object property you access dynamically actually exists:

```typescript
function uppercaseFirst(str: string) {
  return str[0].toUpperCase() + str.slice(1);
}

uppercaseFirst('') // runtime error BAD!!!
```

In the example above, the function will throw an error if the string is empty, because str\[0\] returns undefined and doesn't have a toUpperCase function. TypeScript doesn't warn you about that, regardless of whether strict mode is enabled or not. This is a huge hole in type safety.

The flag noUncheckedIndexedAccess will plug that hole and force you to deal with the possible undefined:

```typescript
function uppercaseFirst(str: string) {
  return str[0]?.toUpperCase() + str.slice(1); // note: ? nullish operator
}

uppercaseFirst('') // returns ''
```

So, why can't we just turn on noUncheckedIndexedAccess? You can, but in a large codebase like that of Flux.ai, you are likely to get thousands of type errors. We had 2761 errors across 373 files! For one speedy engineer converting one file every minute, it would have taken 6+ hours of mind-numbing work to convert all 373 files.

The solution we describe here is how to smoothly convert your codebase with some simple heuristics and automation.

### Heuristics

According to Wikipedia, [a heuristic technique](https://en.wikipedia.org/wiki/Heuristic)

> is any approach to problem solving or self-discovery that employs a practical method that is not guaranteed to be optimal, perfect, or rational, but is nevertheless sufficient for reaching an immediate, short-term goal or approximation.

That is definitely true here.

The goal was to get the codebase compiling with the new flag, not to fix any bugs. The fixing can come later.

To that end, we intentionally added [type assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator) ! to suppress all new type errors from undefined types without changing the runtime behavior of the code.

```typescript
const firstLetter = str[0] // needs too be str[0]!
const rest = str.slice(1)
const upperFirst = firstLetter.toUpperCase()
```

Expanding the scope of replacements to preceding lines allowed us then to automate more fixes with few false positives.

### Automation

The full script we ran on our codebase is below. Note: it did not fix all the errors. It fixed around 2400 out of 2761 errors, leaving around 100 files for us to fix by hand.

Pro-tip: when experimenting with the replacers and precede, you can simply reset your changes with git reset --hard HEAD (assuming you are working in a git repo).

```typescript
#!/usr/bin/env ts-node

// To generate noUncheckedIndexedAccess.txt, run
// $ npx tsc | grep 'error T' > noUncheckedIndexedAccess.txt

import {readFileSync, writeFileSync} from "fs";

type ErrorLines = {path: string; lineNum: number; message: string}[];

// NOTE: these should be idempotent for safety!
const replacers: [RegExp, string][] = [
    [/(\w+\.\w+\.\w+)\.(\w+)/g, "$1!.$2"], // a.b.c.d to a.b.c!.d
    [/(\w+\[(\w|\.)+\])!*/g, "$1!"], // add ! after []
    [/(\w+\])(\[\w+\])/g, "$1!$2"], // add ! between [][]
    [/(\[\w+\])(\.\w+)/g, "$1!$2"], // add ! between [] and .
    [/(\[\d\]?)!*/g, "$1!"], // add ! after [0]
    // START CORRECTIONS
    [/\]!\) =>/g, "]) =>"], // correcting add ! above
    [/\]! =/g, "] ="], // correcting add ! above
];

const precede = 2;

function main() {
    const txt = readFileSync("./noUncheckedIndexedAccess.txt", "utf-8");
    const errorLines = parseErrorLines(txt);
    errorLines.forEach((errorLine) => {
        let lineText = readLine("../" + errorLine.path, errorLine.lineNum, precede) as string;
        replacers.forEach(([match, replacement]) => {
            const newLineText = getNewLineText(lineText, match, replacement);
            if (newLineText) lineText = newLineText;
        });
        console.log("\n---");
        console.log(errorLine.path, errorLine.lineNum, "\n", lineText);
        console.log("---\n");
        writeLine("../" + errorLine.path, errorLine.lineNum, lineText, precede);
    });
}

function getNewLineText(lineText: string, match: RegExp, replacement: string) {
    return (
        lineText
            .split("\n")
            // @ts-ignore: ignore missing string method
            .map((line) => line.replaceAll(match, replacement))
            .join("\n")
    );
}

function parseErrorLines(txt: string): ErrorLines {
    return txt
        .split("\n")
        .filter(Boolean)
        .map((line) => {
            const [pathPlus, message] = line.split(": error ");
            const pieces = pathPlus?.split("(");
            if (!pieces || !pieces[0] || !pieces[1] || !message) {
                throw new Error(`Missing bits in line: ${line}`);
            }
            const numberPieces = pieces[1].split(",", 1);
            if (!numberPieces || !numberPieces[0]) {
                throw new Error(`Missing numbers in pieces: ${pieces}`);
            }
            const lineNum = parseInt(numberPieces[0], 10);
            if (!(lineNum > 0 && lineNum < 1000000)) {
                throw new Error(`Bad line number: ${lineNum}`);
            }
            return {
                path: pieces[0],
                lineNum,
                message,
            };
        });
}

function readLine(filename: string, lineNum: number, precede: number) {
    const lines = readFileSync(filename, "utf8").split("\n");
    return lines.slice(lineNum - 1 - precede, lineNum).join("\n");
}

function writeLine(filename: string, lineNum: number, lineText: string, precede: number) {
    const lines = readFileSync(filename, "utf8").split("\n");
    lines.splice(lineNum - 1 - precede, precede + 1, ...lineText.split("\n"));
    writeFileSync(filename, lines.join("\n"));
}

main();
```

## About the author

Greg Dingle

Software Engineer at Flux

Building the future with friends

Let’s start building

Build your big idea together with Flux. All you need to do is describe what you want to make, or what problem you want to solve. Flux will work with you to make it a reality.

![Close-up photo of a PCB made with Flux, with an ESP32 module, buttons, and a microSD slot.](https://www.flux.ai/p/assets/blogs/miscellaneous/sidebar-cta-pcb.webp) [Try it Free](https://www.flux.ai/signup)

## Related Content

[

![PCB Design for Manufacturability (DFM): Rules and Best Practices](https://www.flux.ai/p/assets/blogs/pcb-design-for-manufacturability-dfm/main.webp)

### PCB Design for Manufacturability (DFM): Rules and Best Practices

8 Min Read](https://www.flux.ai/p/blog/pcb-design-for-manufacturability-dfm)[

![An electronic device taken apart, with every component laid out. Anyone who buys a product can do this, so a trade secret that a teardown would reveal stops being a trade secret once the product ships.](https://www.flux.ai/p/assets/blogs/fearn-defensive-publication/main.webp)

### What is a Defensive Publication? (vs. Patents and Trade Secrets)

7 Min Read](https://www.flux.ai/p/blog/what-is-a-defensive-publication)[

![Schematic diagram of arduino uno board with all of its passive and active components](https://www.flux.ai/p/assets/blogs/arduino-uno-schematic-diagram/main.webp)

### Arduino Uno Schematic Diagram: A Comprehensive Guide

8 Min Read](https://www.flux.ai/p/blog/arduino-uno-schematic-diagram)[

![Top 10 Popular Microcontrollers for Embedded Systems including STM32F103C8T6, ESP32, ESP8266, ATtiny85, PIC16F877A, ATmega32U4, ATmega328P, and more. Essential MCUs for IoT, DIY projects, and professional PCB designs with key features like Wi-Fi, USB, and Bluetooth support.](https://www.flux.ai/p/assets/blogs/top-10-popular-mcu/main.webp)

### Design Your First PCB: 10 Popular Microcontrollers to Get Started

5 Min Read](https://www.flux.ai/p/blog/design-your-first-pcb-10-popular-microcontrollers-to-get-started)[

![3d rendered of an ESP8266 microcontroller board, showing its compact size with the Wi-Fi module, chip antenna, and GPIO pins clearly visible, ideal for embedding wireless internet connectivity into DIY electronics projects.](https://www.flux.ai/p/assets/blogs/everything-about-esp8266/main.webp)

### ESP8266 Pinout Guide: Complete GPIO Reference & IoT Project Tips

10 Min Read](https://www.flux.ai/p/blog/esp8266-pinout-everything-you-need-to-know)[

![Attiny85 chip in two different packages viewed on top, also showing pinout diagram](https://www.flux.ai/p/assets/blogs/attiny85/main.webp)

### Introduction to the ATtiny85 Microcontroller

12 Min Read](https://www.flux.ai/p/blog/introduction-to-the-attiny85-microcontroller)

See All (6)

## Let’s start building.

Let’s build your idea together. All you need to do is describe what you want to make, or what problem you want to solve. Flux will work with you to make it a reality.

[Try it Free](https://www.flux.ai/signup)

 ![Close-up of a Flux-designed printed circuit board](https://www.flux.ai/p/assets/homepage-v2/mission-visual.webp)
