(Part 2)
(Part 2)
function add(nr1: number, nr2: number): number {
return nr1 + nr2;
}
Strong typing
Compilation (transpilation) step
class User {
firstName: string;
lastName: string;
constructor(fn: string, ln: string) {
this.firstName = fn;
this.lastName = ln;
}
greet(): void {
console.log(`I'm ${this.getFullName()}`);
}
private getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
var User = /** @class */ (function () {
function User(fn, ln) {
this.firstName = fn;
this.lastName = ln;
}
User.prototype.greet = function () {
console.log("I'm " + this.getFullName());
};
User.prototype.getFullName = function () {
return this.firstName + " " + this.lastName;
};
return User;
}());
target:
ES5
Traces transpiled files back to the original content
Great for debugging
(from RisingStack blog)
interface HttpResponse {
body: string;
status: number;
}
const res: HttpResponse = {
body: 'Hello World',
status: 200
};
type HttpResponse = {
body: string;
status: number;
}
const res: HttpResponse = {
body: 'Hello World',
status: 200
};
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right',
}
console.log(Direction.Up); // Up
var Direction;
(function (Direction) {
Direction["Up"] = "Up";
Direction["Down"] = "Down";
Direction["Left"] = "Left";
Direction["Right"] = "Right";
})(Direction || (Direction = {}));
console.log(Direction.Up); // Up
target:
ES5
type HttpMethod = 'GET';
const hm1: HttpMethod = 'GET';
// OK
const hm2: HttpMethod = 'test';
// ERROR: Type '"test"' is not
// assignable to type 'HttpMethod'.
const hm3: HttpMethod = null;
// ERROR: Type 'null' is not
// assignable to type 'HttpMethod'.
type HttpGET = {
params: string[];
};
type HttpPOST = {
body: any;
};
type HTTPRequest = HttpGET | HttpPOST;
class Collection<T> {
private collection: T[];
constructor(...items: T[]) {
this.collection = items;
}
get(index: number): T {
return this.collection[index];
}
}
const users = new Collection(
{ name: 'Kevin' },
{ name: 'John' }
);
users.get(0).name;
// OK
users.get(0).age;
// Property 'age' does not
// exist on type...
@Controller('user')
export class UserController {
constructor(private userService: UserService) {}
@Post()
save(@Body() user: User): User {
return this.userService.save(user);
}
@Get()
findAll(): User[] {
return this.userService.findAll();
}
}