Ask Your Question
4

How can a TypeScript generic be utilized to limit function parameters while not retaining the type of the argument?

asked 2022-10-01 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-04 08:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-01 11:00:00 +0000

Seen: 11 times

Last updated: Oct 04 '22