What are K,T, and V in TypeScript Generics?
function foo <T>(value: T) : T {
return value;
}
- from the above example, the T is a generic type parameter which is a type placeholder we pass to the foo function.
- type can be chained to the parameter type and the return value type like (value: T) : T
- T is just a generic name for Type and can be replaced with any valid name.
1) K(Key) : type of key on the object.
2) V(Value) : type of value in the object.
3) E(Element) : the element type.
more than one type parameters can be assigned as below.
function foo<T, U>(value: T, message: U): T {
console.log(message);
return value;
}
console.log(foo<number, string>(11, "콘솔로그")
- from the above example, when we call foo function inside our console.log number type is assigned to type T and it is passed to value and return type.
- we do not HAVE to specify the actual stype and let TypeScript automatically complete the type inference for us.