up:: Coding
Typescript is a strongly typed language, created and maintained by Microsoft as subset of JavaScript. It compiles to JavaScript. It is supported by all major libraries and frameworks.
Typescript is used by Vue, React, Angular.
It keeps application free from type errors, undefined and null values.
To install typescript on Windows, you can use command:
npm install -g typescript // installs typescript globally
Global option reduces the risk of appearing this error:
If you want to run code made in typescript (e.g. name.ts
), first convert it to javascript by using tsc
command. Then you can type and execute node name
command, which will execute converted JavaScript code.
Before using boolean in TypeScript, you need to assign a value to it. Other way you'll get an error.
It is possible to create functions in various ways, for example:
by declaration
function add(num1:number,num2: number): number{
return num1 + num2
using lambda expression
const sub = (num1: number, num2: number): number => num1 - num2;
using function keyword
const mult = function(num1: number, num2: number) : number {
return num1 * num2
}
function add(num1: number, num2: number, ...num3: number[]): number {
return num1 + num2 + num3.reduce((a, b) => a + b, 0);
}
let numbers = [1,2,3];
console.log(add(1, 2, ...numbers));
console.log(add(1, 2, ...[1,2,3]));
console.log(add(1, 2, 1,2,3));
To calculate numbers in array you can use reduce
function.
function add(num1: number, num2: number, ...num3: number[]): number {
return num1 + num2 + num3.reduce((a, b) => a + b, 0);
}
console.log(add(1, 2));
function getItems<Type>(items: Type[]): Type[] {
return new Array<Type>().concat(items);
}
class Employee {
id!: number;
name!: string;
address!: string;
}
let john = new Employee();
john.id = 1;
john.name = "John";
john.address = "Burkina Faso 13";
console.log(john);
By default, all parameters are public.
You can define them private with private
keyword or #
symbol. It is also possible to declare protected properties.
In TypeScript you can't have multiple constructors. Instead, you can use either parameterless or with parameters.
class Employee {
id: number;
name: string;
address: string;
constructor(id: number, name: string, address: string) {
this.id = id;
this.name = name;
this.address = address;
}
}
let john = new Employee(1, "John", "123 Main St");
console.log(john);
Within a class you can add not only the constructor, but also methods. Example below includes interpolation
`${}`
getNameWithAdress(): string {
return `${this.name} ${this.address}`;
}
The extends
keyword on an interface
allows you to effectively copy members from other named types, and add whatever new members you want.
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
interface ColorfulCircle extends Colorful, Circle {}
const cc: ColorfulCircle = {
color: "red",
radius: 42,
};
Title | Language |
---|