Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.