DEV Community

Cover image for How to define basic types in Typescript
Bayu Setiawan
Bayu Setiawan

Posted on

How to define basic types in Typescript

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;
Enter fullscreen mode Exit fullscreen mode
  • String
let course: string = 'Typescript';
Enter fullscreen mode Exit fullscreen mode
  • Boolean
let isLoading: boolean = true;
Enter fullscreen mode Exit fullscreen mode
  • Any
let book;
Enter fullscreen mode Exit fullscreen mode
function render(document: any) {
  console.log(document);
}
Enter fullscreen mode Exit fullscreen mode
  • Array
let arrayOfNumber: number[] = [1, 2, 3];
let arrarOfString: string[] = ['apple', 'orange'];
let arrayOfAny = [];
Enter fullscreen mode Exit fullscreen mode
  • Tupple
let tupples: [number, string] = [1, 'ayam'];
Enter fullscreen mode Exit fullscreen mode
  • Enum
const enum Size {
  Small = 1,
  Medium,
  Large,
}

let mySize: Size = Size.Medium;
console.log(mySize); // 2
Enter fullscreen mode Exit fullscreen mode
  • Object
let employee: {
  readonly id: number;
  name: string;
  retire: (date: Date) => void;
} = {
  id: 1,
  name: 'bayu',
  retire: (date: Date) => {
    console.log(date);
  },
};
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
codebayu profile image
Bayu Setiawan

Hi, kindly leave a like and comment if you got new insight! 🔥