when it comes to something like this in TS generics: function fn<T, U>(...)
, i.e. a couple of types inside angle brackets, what do they really mean? What's the purpose of having more than one generic type inside <>
? Params can be either T
or U
?
CodePudding user response:
The types defined inside the angle brackets are separate. The definition function fn<T, U>(...)
means that fn
function requires 2 type parameters - T
and U
- and that's it. They can be the same type at the context of fn
's consumer, but are parameters defined as T
and U
in the fn
function's context.
A use case for having more than one generic type could be the Pick
type which is a TypeScript builtin utility type:
Pick<Type, Keys>
Constructs a type by picking the set of properties
Keys
(string literal or union of string literals) fromType
.Example
interface Todo { title: string; description: string; completed: boolean; } type TodoPreview = Pick<Todo, "title" | "completed">; const todo: TodoPreview = { title: "Clean room", completed: false, };
We pass 2 types to Pick
:
Type
- which in this case isTodo
, andKeys
- which in this case is"title" | "completed"
. Notice how the definition says thatKeys
is either a string literal or union of string literals. That means thatKeys
would be defined asKeys extends string
, but is actually defined asKeys extends keyof Type
- restricting the type passed toPick
asKeys
to only thestring
s that are keys ofType
.
What we achieve is TodoPreview
which is basically a subset of Todo
, consisting only of the keys "title"
and "completed"
.
CodePudding user response:
The purpose is to constrain the signature according to those types.
Here is some good info from the documentation: TypeScript Generics
Essentially, when you have something like the following, you're just trying to relate all the types together in some way. This code would just check 3 differently typed parameters and return if all of them are truthy.
function myFunc<A, B, C>(param1: A, param2: B, param3: C): boolean {
return !!param1 && !!param2 && !!param3;
}
Because the types are generic, you can't be too restrictive because the whole point of generics is to give consumers flexibility. This works great when you use the keyof
and typeof
syntax to relate one type to the other.