Skip to content

TypeScript config

While Typesaurus will work with any TypeScript config, it’s recommended to use the following tsconfig.json:

{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true
}
}

exactOptionalPropertyTypes

One recommended option exactOptionalPropertyTypes is not well known, especially to TypeScript beginners, because strict does not include it. However, it’s crucial and will cause runtime errors where you don’t expect them.

This option makes such a code invalid and shows a type error:

interface User {
firstName: string;
lastName?: string;
}
const user: User = {
firstName: "Sasha",
lastName: undefined,
};
//=> Type '{ firstName: string; lastName: undefined; }' is not assignable to type 'User' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.
//=> Types of property 'lastName' are incompatible.
//=> Type 'undefined' is not assignable to type 'string'.(2375)

With this option, to allow setting undefined to an optional field, you have to specify it explicitly:

interface User {
firstName: string;
lastName?: string | undefined;
}

At first glance, it might seem like a nuisance, but consider the following example:

function updateUser(data: Partial<User>) {
Object.assign(user, data);
}
updateUser({ firstName: undefined });

The code above would be valid without the option, but it would set the user into an impossible state and ultimately cause runtime errors.