# TypeScript 5.4: the new NoInfer utility

> The new NoInfer<T> utility introduced in TypeScript 5.4 to control generic type inference, with practical examples.

- Autore / Author: Diego Betto (https://diegobetto.com/about/)
- Pubblicato / Published: 2024-02-05
- URL: https://diegobetto.com/en/typescript-noinfer-utility/
- Tag: typescript, javascript, 5.4, inference

The release of [TypeScript 5.4](https://devblogs.microsoft.com/typescript/announcing-typescript-5-4-beta/) brings several new features, among them a new `NoInfer<T>` utility.

### Why was the `NoInfer` utility introduced?

The need arises from the fact that it's often not possible to correctly infer which values a given argument can take.
For example, if we write a function that accepts:

- a list of possible animals;
- a default animal;

```js
function displayAnimal<A extends string>(animals: A[], defaultAnimal?: A) {
    // ...
}

displayAnimal(["dog", "cat", "turtle"], "dog");
```

it's very likely we'd expect `defaultAnimal` to be set to one of the possible ones.
Currently, with the type definition above, this isn't always guaranteed. In fact, a call like this remains valid, even if undesirable:

```js
displayAnimal(["dog", "cat", "turtle"], "crocodile");
```

### The solution

This is why the `NoInfer` utility was introduced, letting us tell TypeScript not to analyze and not to consider the value we pass to `defaultAnimal` as valid for the generic `A`.

```js
function displayAnimal<A extends string>(animals: A[], defaultAnimal?: NoInfer<A>) {
    // ...
}

displayAnimal(["dog", "cat", "turtle"], "crocodile");
//                                       ~~~~~~~~~
// error!
// Argument of type '"crocodile"' is not assignable to parameter of type '"dog", "cat", "turtle" | undefined'.
```

This way we tell TypeScript to ignore the values `defaultAnimal` could otherwise take, and to only consider the ones from `animals` as possible.

If you're looking for more information:

- [https://github.com/microsoft/TypeScript/pull/56794](https://github.com/microsoft/TypeScript/pull/56794)
- [https://devblogs.microsoft.com/typescript/announcing-typescript-5-4-beta](https://devblogs.microsoft.com/typescript/announcing-typescript-5-4-beta)
