This is my journey to learn TypeScript part 1.
I decided to learn TypeScript to make my code more stable and to add static typing to JavaScript. Static typing means that the type of a variable cannot be changed at any point in a program.
// math.ts
function sum(a: number, b: number) {
return a + b;
}
sum('10', '20'); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.
let str: string = 'hello world';
let num: number = 1;
let boo: boolean = false;
let arr: Array<number> = [1, 2, 3];
let items: nummber[] = [1, 2, 3];
let obj: object = {};
let person: { name: string, age: number} = { name: 'Brian Oh', age: 999 }
let address: [string, number] = ['New York', 11101]
let str: any = 'hi';
let num: any = 10;
let arr: any = ['a', 2, true];
let unuseful: void = undefined;
function notuse(): void {
console.log('sth');
}
How to declare basic types in functions.
function sum(a: number, b: number): number {
return a + b;
}
function sum(a: number, b: number): number {
return a + b;
}
sum(10, 20); // 30
sum(10, 20, 30); // error, too many parameters
sum(10); // error, too few parameters
function sum(a: number, b?: number): number {
return a + b;
}
sum(10, 20); // 30
sum(10, 20, 30); // error, too many parameters
sum(10); // 10
function logText(text: string | number) {
// ...
}
// Using union type function getAge(age: number | string) { if (typeof age === ‘number’) { age.toFixed(); return age; } if (typeof age === ‘string’) { return age; } return new TypeError(‘age must be number or string’); }
- **Intersection Type**
- An intersection type is a type that merges several kinds into one.
interface Person { name: string; age: number; } interface Developer { name: string; skill: number; } type Capt = Person & Developer;
### Type Aliases
- Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.
// Using string type const name: string = ‘brian’;
// Using type aliases type MyName = string; const name: MyName = ‘brian’;
type Developer = { name: string; skill: string; }
type User
npm i typescript -g
tsc filename.ts
tsconfig.json
to set configuration details