Understanding TypeScript Data Types

yuya0114

Yuya Hirano

Posted on February 6, 2023

Understanding TypeScript Data Types

TypeScript is a statically typed language, meaning that every variable in TypeScript has a type. It is important to understand these types to write clean, efficient, and error-free code. This article covers the basic and most commonly used data types in TypeScript, as well as a few additional types that are useful to know.

Number: Used to represent numeric values, such as integers or floating-point numbers.

let a: number = 42;
let b: number = 3.14;
Enter fullscreen mode Exit fullscreen mode

String: Used to represent a sequence of characters.

let name: string = "John Doe";
Enter fullscreen mode Exit fullscreen mode

Boolean: Used to represent true or false values.

let isTrue: boolean = true;
let isFalse: boolean = false;
Enter fullscreen mode Exit fullscreen mode

Array: Used to represent a collection of values of the same type.

let numbers: number[] = [1, 2, 3, 4];
let names: string[] = ["John", "Jane", "Jim"];
Enter fullscreen mode Exit fullscreen mode

Tuple: Used to represent a data structure similar to an array with multiple types.

let user: [string, number] = ["John Doe", 32];
Enter fullscreen mode Exit fullscreen mode

Enum: Used to give named identifiers to numbers or strings.

enum Color {Red, Green, Blue};
let c: Color = Color.Green;
Enter fullscreen mode Exit fullscreen mode

Any: Used to represent any TypeScript type.

let value: any = 42;
value = "Hello";
Enter fullscreen mode Exit fullscreen mode

Void: Used to indicate a function that does not return a value.

function sayHello(): void {
    console.log("Hello!");
}
Enter fullscreen mode Exit fullscreen mode

Never: Used to indicate an error or termination state.

function throwError(): never {
    throw new Error("Something went wrong");
}
Enter fullscreen mode Exit fullscreen mode

These are just a few of the additional TypeScript data types that are available. It's important to understand these types and choose the appropriate one for your specific use case to write efficient and maintainable code.

💖 💪 🙅 🚩
yuya0114
Yuya Hirano

Posted on February 6, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related