Static methods can be called on the class directly:
class Pony {
static defaultSpeed() {
return 10;
}
}
const speed = Pony.defaultSpeed();
const getUser = (login) => {
return new Promise((resolve, reject) => {
if (response.status === 200)
resolve(response.data);
else
reject('No user');
});
};
getUser(login)
.then(user => console.log(user));
If a variable is require to have multiple types exclusively.
let changing: number | boolean = 2;
changing = true;
By default enum starts with 0.
enum Status { Ready, Started, Done }
const progress = Status.Started;
But custom values can also be set.
enum Medal { Gold = 1, Silver, Bronze }
To define generic types in javascript we can:
// A generic class
class Queue<T> {
private list: T[] = [];
push(item: T): void { this.list.push(item); }
pop(): T | undefined { return this.list.shift() }
}
let queue = new Queue<number>();
queue.push(3);
queue.push('4'); // error!
In functional programming we often want to apply a function partially, we can achieve that feat by chaining together multiple fat arrow functions:
// A curried function
const add = (x: number) => (y: number) => x + y;
// Usage
add(123)(456);
// Partially applied
let add123 = add(123);
// fully apply the function
add123(456);
We can set the return type of a function like so:
function startRace(race: Race): Race {
race.status = Status.Started;
return race;
}
If the function returns nothing, return void
.
When a function has an arguments that require a specific property, we can use interfaces to define the “shape” of that object.
function addPointsToScore(player: { score: number; }, points: number): void {
player.score += points;
}
It means that the parameter must have a propert called score
of the type number
. We can name these interfaces like so:
interface HasScore {
score: number;
}
function addPointsToScore(player: HasScore, points: number): void {
player.score += points;
}
JS arguments are optional, but in TypeScript the compiler will complain if parameters with types are forgotten.
We can add a ?
after the parameter to make it optional.
function addPointsToScore(player: HasScore, points?: number): void {
points = points || 0;
player.score += points;
}
type Email: string;
const assertValidEmail = (email: string): asserts email is Email {
if (!email.includes('@'))
throw new Error('Not a valid email.');
}
Utility types are useful generic constructs to perform type transformations, more specifically, on an object. Most used utility types are:
Partial<T>
which transforms all members of T into optionalReadonly<T>
which, well… makes all fields read-only…and many more such as
Record<K,T>
,Pick<T,K>
,Omit<T,K>
etc. which I already know the behaviour of.
type Brand<K, T> = K & { __brand: T };
Afaik, declaration files are used to define what the types of a javascript file are. This is useful for prividing intelisense in your text editor.