Basic Typescript types

TypeScript is a superset of JavaScript that adds optional static typing. This means you can define the data types of variables and functions, leading to improved code clarity, maintainability, and error detection during development. Let's delve into the core building blocks of TypeScript: basic types.

Primitive Types

String

Represents textual data enclosed in single (') or double (") quotes.

				
					let name: string = "Alice";
console.log(name); // Output: "Alice"

				
			

Number

Represents numeric values, including integers and floating-point decimals.

				
					let age: number = 30;
let pi: number = 3.14159;
console.log(age);   // Output: 30
console.log(pi);    // Output: 3.14159

				
			

Boolean

Represents logical values, either true or false.

				
					let isLoggedIn: boolean = true;
let isNight: boolean = false;
console.log(isLoggedIn); // Output: true
console.log(isNight);    // Output: false

				
			

Literal Types

Represent specific string or numeric values.

				
					let greeting: "Hello" = "Hello"; // Only "Hello" allowed
let errorCode: 404 = 404;           // Only 404 allowed

// TypeScript will catch errors like:
// greeting = "Hi"; // Error: Type '"Hi"' is not assignable to type '"Hello"'.
// errorCode = 500;  // Error: Type '500' is not assignable to type '404'.

				
			

Arrays

Represent ordered collections of items of the same or compatible types.

				
					let colors: string[] = ["red", "green", "blue"];
let numbers: number[] = [1, 2, 3.14];

console.log(colors[1]); // Output: "green"
console.log(numbers[2]); // Output: 3.14

				
			

Tuples

Represent fixed-length arrays with specific element types at each position.

				
					let employee: [string, number] = ["John", 35];

// Accessing elements:
console.log(employee[0]); // Output: "John"
console.log(employee[1]); // Output: 35

// TypeScript will catch errors like:
// employee = ["Jane", "Doe"]; // Error: Type 'string' is not assignable to type 'number'. (second element)

				
			

Enums (Enumerations)

Define sets of named numeric constants, improving readability and type safety.

				
					enum Weekday {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday
}

let today: Weekday = Weekday.Wednesday;
console.log(today); // Output: 2 (underlying numeric value)

// Accessing by name:
console.log(Weekday[1]); // Output: "Tuesday"

				
			

Unknown and Any

unknown: Represents a variable with an unknown type. Use cautiously when type information is unavailable. TypeScript might not perform type checking for unknown variables.

				
					let userInput: unknown = prompt("Enter a value");
// You'll need type assertions (explained later) or type guards to use userInput safely.

				
			

any: Disables type checking altogether. Use sparingly, as it bypasses TypeScript’s benefits.

				
					let anything: any = "hello";
anything = 42; // Allowed, but loses type safety

				
			

Void

Represents the absence of a return value from a function.

				
					function sayHi(): void {
  console.log("Hello!");
}

sayHi(); // Output: "Hello!" (function doesn't return anything)

				
			

Null and Undefined

  • null: Represents the intentional absence of a value.
  • undefined: Represents a variable that has been declared but not assigned a value.
				
					let maybeValue: string | null = null; // Can be a string or null
let notAssigned: string; // Declared but undefined

console.log(maybeValue); // Output: null
console.

				
			

Type Assertions

Force a variable to a specific type, but use with caution as it bypasses type checking.

				
					let userInput = prompt("Enter a number (but might be text)");

// TypeScript might not catch errors if userInput is actually text.
let userNumber = userInput as number;
console.log(userNumber + 10); // Potential runtime error if userInput is not a number

// Use type guards (explained later) for safer type conversions.

				
			

By mastering TypeScript's basic types, you'll lay a solid foundation for building type-safe and robust applications. Remember to use type annotations consistently, leverage type guards for safe type assertions, and explore advanced concepts like discriminated unions for complex scenarios. As you progress, delve into more advanced topics like generics, classes, interfaces, and decorators to unlock the full potential of TypeScript for well-structured and maintainable code. Happy coding ! ❤️

Table of Contents