DEV Community

Cover image for A Short Handbook for TypeScript
Mushfiqur Rahman Shishir
Mushfiqur Rahman Shishir

Posted on

A Short Handbook for TypeScript

TypeScript is a programming language that extends JavaScript by adding types. Types are annotations that describe the kind of data that a variable can hold, such as numbers, strings, booleans, arrays, objects, functions, etc.

In this post let’s explore the noteworthy ways to declare and use types, functions, interfaces, generics, and classes in TypeScript.

BENIFITS OF USING TYPES

You might be wondering why bother with types if JavaScript works fine without them, after all!

With TypeScript, you can avoid common errors like typos, null pointer exceptions, or incorrect function calls. You can also refactor your code with confidence, knowing that any changes will be checked by the compiler and flagged if they break something. TypeScript also helps you write more expressive and concise code by providing features like interfaces, generics, unions, intersections, and more. These features allow you to define and manipulate types in powerful ways that are not possible in plain JavaScript. In short, TypeScript makes your life easier as a developer by making your code safer, cleaner, and smarter.

HOW TO USE BASIC TYPES

For TypeScript, there are several built-in types that you can use to define variables, functions, and objects. Here are some examples of TypeScript types and how to use them:

// boolean type
let isDone: boolean = false;

// number types (integer and floating-point)
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

// string type
let color: string = "blue";
let fullName: string = `Bob Bobbington`;
let sentence: string = `Hello, my name is ${fullName}.`;

// array type
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

// tuple type
let x: [string, number];
x = ["hello", 10];

// enum type
enum Color {
  Red,
  Green,
  Blue,
}
let c: Color = Color.Green;

// any type
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;

// void type (function that returns no value)
function warnUser(): void {
  console.log("This is my warning message");
}

// null and undefined types
let u: undefined = undefined;
let n: null = null;
Enter fullscreen mode Exit fullscreen mode

Read the complete post on my blog.

Top comments (0)