DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on • Edited on

NoInfer in Typescript 5.4

I introduce NoInfer which is new feature in TypeScript 5.4.

What is NoInfer?
NoInfer is a feature in TypeScript that suppresses type inference. For example, we have following the code.

const func1 = <T extends string>(array: T[], searchElement: T) => {
  return array.indexOf(searchElement);
};

console.log(func1(["a","b","c"],"d"))
Enter fullscreen mode Exit fullscreen mode

The second argument of func1 is assigned to d, but since d does not exist in the elements of the array in the first argument, an index search returns -1. However, TypeScript does not produce a type error in such a case. This is because both the array passed as the first argument and the string specified as the second argument are used as materials to infer the type T, resulting in the type T being inferred as 'a' | 'b' | 'c' | 'd'. So, how can you produce a type error if a string other than a, b, or c is entered as the second argument? This is where NoInfer can be used.

const func2 = <T extends string>(array: T[], searchElement: NoInfer<T>) => {
  return array.indexOf(searchElement);
};
console.log(func2(["a","b","c"],"b"))// no error
console.log(func2(["a","b","c"],"d"))// error happened. Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c"'
Enter fullscreen mode Exit fullscreen mode

Using NoInfer allows you to stop the type inference expansion at that part. Hence, In this case, the type T is constrained to 'a' | 'b' | 'c', so you can explicitly raise an error when passing 'd' as an argument.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more