BudiBadu Logo
Samplebadu

TypeScript by Example: Types

5.x

Comprehensive guide to TypeScript basic types including primitives, arrays, and tuples. This sample code demonstrates boolean, number, string, array notations, tuple structure, and the any type for flexible typing in your TypeScript applications.

Code

// Boolean
let isDone: boolean = false;

// Number
let decimal: number = 6;
let hex: number = 0xf00d;

// String
let color: string = "blue";

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

// Tuple
let x: [string, number];
x = ["hello", 10]; // OK

// Any (opt-out of type checking)
let notSure: any = 4;
notSure = "maybe a string instead";

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

Explanation

TypeScript enhances JavaScript by adding static type checking, allowing you to declare what types of values your variables, parameters, and return values can hold. This catches type-related errors during development rather than at runtime. The fundamental types like boolean, number, and string mirror JavaScript's primitive values, while arrays can be defined using bracket notation type[] or the generic form Array<type>.

Tuples extend arrays by allowing you to specify exactly how many elements exist and what type each position holds. For instance, [string, number] describes an array with exactly two elements where the first must be a string and the second a number. This is particularly useful for functions that return multiple values or for representing fixed data structures like coordinates.

TypeScript provides several special types for different scenarios:

  • any opts out of type checking - useful for migrating JavaScript code but should be avoided in new code
  • void indicates functions that perform actions but don't return values
  • never represents values that never occur, like functions that always throw errors
  • unknown is a type-safe alternative to any requiring type checks before use

Code Breakdown

2
: boolean is a type annotation specifying the variable type.
12
Array<number> is the generic syntax for typed arrays.
16
[string, number] defines a tuple with fixed types and length.
19
: any disables type checking for this variable.