What are basic types in TypeScript?
TypeScript is a strongly-typed superset of JavaScript that enhances code quality and maintainability by introducing static types. Understanding its basic types is fundamental for building robust applications.
Primitive Types
These are the simplest data types, directly corresponding to JavaScript's primitive values.
Boolean
Represents a logical entity and can have two values: true or false.
let isDone: boolean = false;
let hasStarted: boolean = true;
Number
As in JavaScript, all numbers in TypeScript are floating-point values. They can be decimal, hexadecimal, binary, or octal literals.
let decimal: number = 25;
let hex: number = 0xfd0;
let binary: number = 0b1011;
let octal: number = 0o723;
String
Represents text data. You can use single quotes, double quotes, or backticks (for template strings).
let studentName: string = "Alice";
let greeting: string = `Hello, ${studentName}!`;
Null and Undefined
TypeScript has null and undefined types. By default, they are subtypes of all other types, meaning you can assign null or undefined to number, string, etc. (unless --strictNullChecks is enabled).
let u: undefined = undefined;
let n: null = null;
// When --strictNullChecks is off:
let x: string = "value";
x = undefined; // OK
x = null; // OK
Symbol (ES6)
Introduced in ECMAScript 2015 (ES6), Symbol is a primitive value that represents a unique identifier.
let id1: symbol = Symbol('id');
let id2: symbol = Symbol('id');
// console.log(id1 === id2); // false
BigInt (ES2020)
Represents whole numbers larger than 2^53 - 1, which is the maximum value a number primitive can reliably represent.
let largeNumber: bigint = 1234567890123456789012345678901234567890n;
let anotherLargeNumber: bigint = BigInt("9007199254740991");
Other Fundamental Types
TypeScript also provides several other types that are crucial for building applications, often combining primitives or defining specific behaviors.
Array
Represents a collection of values of the same type. You can declare arrays using two syntaxes.
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["A", "B", "C"];
Tuple
Allows you to express an array where the type of a fixed number of elements is known, but does not have to be the same.
let user: [string, number];
user = ["John Doe", 30]; // OK
// user = [30, "John Doe"]; // Error
Enum
Enums provide a way of giving more friendly names to sets of numeric values. They can be numeric or string-based.
enum LoadState { Loading, Loaded, Error };
let currentState: LoadState = LoadState.Loaded;
enum Direction { Up = "UP", Down = "DOWN", Left = "LEFT", Right = "RIGHT" };
Any
The any type is a powerful way to opt-out of type-checking for a particular value. Variables of type any can be reassigned to any type and can have any property accessed.
let untyped: any = 4;
untyped = "hello";
untyped = false;
untyped.someMethod(); // No error at compile time
Unknown
Similar to any, but safer. Values of type unknown must be narrowed through type checks before they can be used in operations that rely on a specific type.
let value: unknown = "TypeScript";
if (typeof value === 'string') {
console.log(value.toUpperCase()); // OK, 'value' is narrowed to string
}
// let s: string = value; // Error: Type 'unknown' is not assignable to type 'string'.
Void
Used for functions that do not return any value. It's the opposite of any.
function logMessage(message: string): void {
console.log(message);
}
Never
The never type represents the type of values that never occur. It's used for functions that always throw an exception or functions that never return (e.g., an infinite loop).
function throwError(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}