Practical intro to Typescript (Part 1)

Classes in TS

Typescript classes are just a form of sugar syntax for prototypes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class User {
private firstName: String;
private lastName: String;
age: Age;
// By Default everything is public, but we can specify it
public address: String;
// We won't be able to change this property once we assign the value
readonly unchangableProperty: String;
// Static property, only accesible on the class itself
static readonly maxAge = 50;

constructor(first: String, last: String) {
this.firstName = first;
this.lastName = last;
this.unchangableProperty = last;
}

getFullName(): String {
return this.firstName + " " + this.lastName;
}
}

const user = new User("Lucas", "Contre");
console.log(user.getFullName());
console.log(User.maxAge);

Interfaces, Inheritance and Classes

1
2
3
4
5
6
7
8
9
// Inheritance
class Admin extends User {}
interface UserIface {
getFullName(): String;
}

class User implements UserIface {
// This class must implement the interface
}

Generics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const addId = <T extends object>(obj: T) => {
// The `extends` is not neccesary but is nice when we konw which type we want to receive
const id = Math.random().toString(16);
return {
...obj, // Unpack all the properties of the object
id,
};
};

// We can now do somehting like this
const user = { name: "Jack" };
const result = addId(user);
// But it would be nicer to do something like
interface UserIface {
name: String;
}
const nicerUser: UserIface = {
name: "Jack Sparrow",
};
const saferResult = addId<UserIface>(user);

Generics with Interfaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface PersonInterface<T, V> {
name: string;
data: T;
age: V;
}

const person: PersonInterface<{ meta: String }, Number> = {
name: "John",
age: 33,
data: {
meta: "Hello",
},
};

const person2: PersonInterface<String[], String> = {
name: "Juan",
age: "33",
data: ["s1", "s2"],
};

Enums ? Yes, Enums

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
enum Status {
NotStarted,
InProgress,
Done,
}

console.log(Status.NotStarted); // 0
console.log(Status.InProgress); // 1
console.log(Status.Done); // 2

// Enums are a type
let initialStatus: Status = Status.NotStarted;

initialStatus = "Hi"; // This won't work
initialStatus = Status.Done; // This will

// A common use case would be
interface Task {
id: string;
status: Status;
}

Of course we are missing classic things like loops and some specific types, but I guess you can figure out those by yourself.

Most examples where taken from this video


Author: Lucas Contreras