Typescript
Implicit Type Declaration
let num = 10; \\ Now the variable num can only store number values
Predefined Type for variables
const name: string;
Primitive Data Types
const number: number = 10;
const string: string = "Rishabh";
const boolean: boolean = true;
Array
const numbers = [1, 2, 3];
const numbers: number[];
const numbers: number[] = [1, 2, 3];
Union
const number: number | string = process.argv[2];
const bools: (number | boolean)[] = [0, true];
Objects -> Explicit declaration can only be done on let variables, const variables cannot be declare explicitly. Explicit declaration can be done used type or interface keyword.
// Implicit Declaration
const person : {
name: 'Rishabh',
age: 23
}
// Explicit Declaration
let person: {
name: string;
age: number;
}
person = {
name: 'Rishabh'
age: 23
}
Optional Variable -> When not sure about if the variable will be required in all scenarios.
let person: {
name: string;
age: number;
phone: string;
};