One way to limit function parameters while not retaining the type of the argument is to use a type parameter with a constraint that specifies a union of allowed types.
For example, suppose we have a function that takes two arguments, a
and b
, and we want to limit a
to be a string or number, but we don't want to retain the specific type of a
in the return type:
function myFunc<T extends string | number>(a: T, b: any) {
// do something with a and b
}
myFunc("hello", 42); // OK
myFunc(true, null); // Error: 'true' is not assignable to string | number
In this example, T
is a type parameter with a constraint of string | number
, which limits the possible types for a
. However, the return type of myFunc
does not include T
, so the specific type of a
is not retained.
Asked: 2022-10-01 11:00:00 +0000
Seen: 11 times
Last updated: Oct 04 '22