Real-world TypeScript development - Textnotes

Real-world TypeScript development


Learn TypeScript basic data types with clear explanations and practical examples. This tutorial covers string, number, boolean, null, undefined, any, unknown, void, and never for real-world TypeScript development.

1. String

The string type is used to represent textual data. In TypeScript, strings can be defined using single quotes, double quotes, or template literals.

Example


let firstName: string = "Muni";
let lastName: string = 'Kumar';

let fullName: string = `${firstName} ${lastName}`;

Strings ensure that only text values are assigned, preventing accidental assignment of numbers or objects.

2. Number

The number type represents both integer and floating-point values. TypeScript does not differentiate between int and float.

Example


let age: number = 35;
let salary: number = 55000.75;

Any attempt to assign a non-numeric value will result in a compilation error.

3. Boolean

The boolean type represents logical values: true or false.

Example


let isActive: boolean = true;
let isLoggedIn: boolean = false;

Booleans are commonly used in conditions, flags, and feature toggles.

4. Null and Undefined

null and undefined represent absence of value.

  1. undefined means a variable is declared but not assigned.
  2. null means a variable is explicitly set to have no value.

Example


let result: undefined = undefined;
let data: null = null;

With strict null checks enabled, null and undefined must be handled explicitly.

Example with Strict Mode


let username: string | null;
username = null;
username = "Muni";

5. Any and Unknown

Any

The any type disables type checking. It allows assigning any value and calling any method.

Example


let value: any = 10;
value = "text";
value = true;

Using any removes TypeScript’s safety and should be avoided in production code.

Unknown

The unknown type is safer than any. You must perform type checks before using the value.

Example


let input: unknown;
input = "Hello";

if (typeof input === "string") {
console.log(input.toUpperCase());
}

unknown is recommended when dealing with external data such as API responses.

6. Void and Never

Void

The void type is used for functions that do not return any value.

Example


function logMessage(message: string): void {
console.log(message);
}

Never

The never type represents values that never occur. It is commonly used for functions that always throw errors or never complete.

Example


function throwError(message: string): never {
throw new Error(message);
}

Another example is an infinite loop:


function infiniteLoop(): never {
while (true) {}
}

Conclusion

Understanding basic data types is fundamental to mastering TypeScript. Strong typing improves code safety, readability, and maintainability. Choosing the correct data type helps prevent bugs and ensures predictable behavior in real-world applications.