DAY 21 OF 30
Generics
Yesterday, in one sentence
A type but also a set of named values, written with the enum keyword. It
compiles to an object in JavaScript, and as a type it accepts only its own
members.
Did you say:
- ✓a type but also a set of named values
- ✓written with the `enum` keyword
- ✓compiles to an object in JavaScript
- ✓as a type it accepts only its own members
Interview question
A literal union is a type only and is stripped out at build time. An enum is also a set of named values and compiles to an object. The literal union uses structural typing and accepts any matching value. The enum does not, and accepts only its own members.
Did you say:
- ✓a literal union is a type only, stripped out at build time
- ✓an enum is also a set of named values and compiles to an object
- ✓the literal union uses structural typing
- ✓the enum accepts only its own members
You may have two functions that do exactly the same thing but just expect different types. A generic functionGeneric Function lets you write one function with the type as a parameter, decided when the function is called. This prevents you from writing the same function twice.
type Hero = { good: boolean };
type Villain = { evil: boolean };
function getFirstHero(heroes: Hero[]): Hero {
return heroes[0];
}
function getFirstVillain(villains: Villain[]): Villain {
return villains[0];
}
The body of getFirstHero is identical to the body of getFirstVillain. Only the
types differ.
A generic function declares a type parameter in angle brackets after the function name.
function getFirst<T>(items: T[]): T {
return items[0];
}
T is the type parameter. It is used for the function parameter as T[] and again
as the return typeReturn Type, so all three refer to the same type.
When the function is called, TypeScript infers what T is from the argument.
getFirst(heroes);
// TypeScript reads it as: getFirst<Hero>(items: Hero[]): Hero
getFirst(villains);
// TypeScript reads it as: getFirst<Villain>(items: Villain[]): Villain
A type aliasType Alias can declare a type parameter too, making it a generic typeGeneric Type.
type Pair<T> = {
first: T;
second: T;
};
let ranks: Pair<number> = { first: 1, second: 2 };
There is no argument here for TypeScript to infer from, so you pass the type in the angle brackets yourself when you use the alias.
Check yourself
wrap("Logan")?
function wrap<T>(value: T): T[] {
return [value]
}
TypeScript infers T as string. It does not keep the literal type "Logan", because the argument is being passed to a parameter that could hold any string.
A generic function or type declares a type parameter in angle brackets, which stands in for a type that is decided when the code is used. It means one definition works with many types, instead of repeating it for each one.
Did you say:
- ✓a type parameter declared in angle brackets
- ✓stands in for a type decided when the code is used
- ✓one definition works with many types