Understanding TypeScript Type Annotations for Variables

Saurabh Mhatre
2 min readJun 1, 2023

--

Understanding TypeScript Type Annotations for Variables

TypeScript’s type annotations allow developers to explicitly declare the types of variables, enhancing code readability and enabling static type checking. In this short article, we will explore TypeScript’s type annotations for different types of variables and understand how they contribute to type safety.

1. Basic Types:
- Number: Use `number` to declare variables that hold numeric values.
- String: Declare variables that store textual data using the `string` type.
- Boolean: Use `boolean` for variables that represent true or false values.
- Array: Declare variables as arrays using the syntax `type[]` or `Array<type>`.

Example:


let age: number = 25;
let name: string = "John Doe";
let isAdmin: boolean = false;
let numbers: number[] = [1, 2, 3];
let fruits: Array<string> = ["apple", "banana", "orange"];

2. Object Types:
- Object: Use the `object` type when the variable can hold any non-primitive value.
- Custom Objects: Define interfaces or classes to create custom object types.

Example:


let person: object = { name: "John", age: 30 };
let user: { id: number; name: string } = { id: 1, name: "Alice" };

3. Union Types:
- Union types allow variables to hold values of multiple types.
- Use the `|` operator to specify the possible types.

Example:


let score: number | string = 100;
score = "high";

4. Any Type:
- The `any` type represents variables that can hold values of any type.
- Avoid using `any` when possible, as it bypasses type checking.

Example:

let dynamicValue: any = "dynamic";
dynamicValue = 123;

5. Type Inference:
- TypeScript's type inference automatically infers the type based on the assigned value.
- Type inference eliminates the need for explicit type annotations in certain cases.

Example:


let inferredNumber = 42; // Inferred as number
let inferredString = "Hello"; // Inferred as string
let inferredArray = [1, 2, 3]; // Inferred as number[]

Conclusion:
TypeScript's type annotations allow developers to explicitly declare the types of variables, enhancing code clarity and enabling static type checking. By utilizing type annotations, developers can improve type safety, catch potential errors at compile-time, and enhance the development experience. Understanding the different types and their usage ensures more robust and reliable TypeScript code.

That’s it from my end for today. Have a nice day ahead 😁

P.S. Check out my Youtube channel here for more content:- https://youtube.com/@SaurabhNative

--

--

Saurabh Mhatre
Saurabh Mhatre

Written by Saurabh Mhatre

Senior Frontend Developer with 9+ years industry experience. Content creator on Youtube and Medium. LinkedIn/Twitter/Instagram: @SaurabhNative

No responses yet