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"))
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"'
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.
Top comments (0)