In TypeScript, you can define basic types using a combination of built-in primitive types and custom types.
Here are some of the essential basic types:
- Number
let amount: number = 20;
- String
let course: string = 'Typescript';
- Boolean
let isLoading: boolean = true;
- Any
let book;
function render(document: any) {
console.log(document);
}
- Array
let arrayOfNumber: number[] = [1, 2, 3];
let arrarOfString: string[] = ['apple', 'orange'];
let arrayOfAny = [];
- Tupple
let tupples: [number, string] = [1, 'ayam'];
- Enum
const enum Size {
Small = 1,
Medium,
Large,
}
let mySize: Size = Size.Medium;
console.log(mySize); // 2
- Object
let employee: {
readonly id: number;
name: string;
retire: (date: Date) => void;
} = {
id: 1,
name: 'bayu',
retire: (date: Date) => {
console.log(date);
},
};
- Function
// without parameter
function calculateTax(): number {
return 10;
}
// number parameter
function calculateTax2(income: number): number {
if (income > 50000) return income * 2;
return income * 1;
}
// number multiple parameter
function calculateTax3(income: number, taxYear: number): number {
if (taxYear > 2022) return income * 2;
return income * 1;
}
calculateTax3(10000, 2021);
// multiple & optional parameter
function calculateTax4(income: number, taxYear?: number): number {
if ((taxYear || 2022) > 2022) return income * 2;
return income * 1;
}
calculateTax4(10000);
// multiple, optional & default value parameter
function calculateTax5(income: number, taxYear = 2022): number {
if (taxYear > 2022) return income * 2;
return income * 1;
}
calculateTax5(10000);
Defining basic types in TypeScript is crucial for writing maintainable and error-free code. By specifying types explicitly, you can catch errors early in the development process and improve code readability. TypeScript provides a range of built-in primitive types, as well as the flexibility to create custom types, enabling you to create structured and organized applications.
Hope this helps!
Top comments (1)
Hi, kindly leave a like and comment if you got new insight! 🔥