DAY 13 OF 30
Typing Functions
Yesterday, in one sentence
as const do in TypeScript?It tells TypeScript to infer the narrowest possible type from a value and make it readonly. Values keep their literal types, and arrays become readonly tuples.
Did you say:
- ✓infers the narrowest possible type
- ✓makes everything readonly
- ✓arrays become readonly tuples
Interview question
A type whose only allowed value is one exact value. You use them in a union to list every value something can be, so anything outside that list is an error.
Did you say:
- ✓a type with one exact allowed value
- ✓used in a union to list every allowed value
- ✓anything outside that list is an error
You add a type annotationType Annotation to a function parameter with a colon after its name. Parameters have to be annotated, because there is no value to infer from until the function is called.
function greet(name: string) {
return `hello ${name}`;
}
greet("Jean"); // ok
greet(41); // ❌ Argument of type 'number' is not assignable to
// parameter of type 'string'
You can also set the type for the value a function returns. This is called the return type, and you write it with a colon after the parameter brackets.
function level(name: string): number {
return name.length;
}
TypeScript can read what you return and work the return type out for itself, so annotating it is optional.
const double = (level: number) => level * 2; // return type inferred as number
A ? after a parameter name makes it an optional parameter. This works like an
optional property. The caller can leave the argument out, so inside the function the
parameter is inferred as a union typeUnion Type of the declared
type and undefined.
function recruit(team?: string) {
// team is string | undefined
}
Setting a default value on a parameter makes it a default parameter. The argument
can be left out and the parameter falls back to that value, so TypeScript always
infers the type from the default value, as shown in the example below as a string.
function recruit(team = "mutants") {
// team is string
}
A rest parameter collects any number of remaining arguments into an array, so it should be annotated with an array typeArray Type.
function assemble(...members: string[]) {
// members is string[]
}
assemble("Scott", "Jean", "Logan");
Check yourself
name and team?
function recruit(name = "hero", team?: string, ...powers: string[]) {}
name is a default parameter, so it always has a value and is inferred as string. team is an optional parameter, so it may be left out and is string | undefined.
A colon after each parameter name, and a colon after the brackets for the return type. Parameters must be annotated, the return type is usually inferred.
Did you say:
- ✓a colon after each parameter name
- ✓a colon after the brackets for the return type
- ✓parameters must be annotated, the return type is usually inferred