🔷 TypeScript Q2 / 100

What are basic types in TypeScript?

AI-Powered Answer ✓ Answered

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.

typescript
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.

typescript
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).

typescript
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).

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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).

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

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