Skip to main content

Decoding tsconfig options - noUncheckedIndexedAccess

The noUncheckedIndexedAccess option in TypeScript is a useful feature that helps to write safer code. But it is not enabled by default and unfortunately stays disabled even when using Typescript's "strict" configuration. This, sadly, often results in the option being overlooked and unused.

So, what is noUncheckedIndexedAccess, and in how does it affect type-checking?

Example with objects

Let's consider this small example where noUncheckedIndexedAccess is disabled and we try to group users by role, by looping over the users array and adding them to an userByRole object:

type User = {
name: string;
role: string;
};

const groupUsersByRole = (users: Array<User>) => {
let userByRole: Record<string, Array<User>> = {};

users.forEach((user) => {
userByRole[user.role].push(user);
});

return userByRole;
};

const users: Array<User> = [
{ name: "John", role: "Admin" },
{ name: "Martin", role: "Moderator" },
];

const usersByRole = groupUsersByRole(users);

This might not be obvious at first because Typescript seems very happy with it all, but this code will blow up at runtime 😱