
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.
The release of TypeScript 5.4 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;
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:
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.
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: