Historical archive
TypeScript Basics: Types, Interfaces, Classes, and Functions
Introductory TypeScript notes covering primitive types, arrays, tuples, enums, interfaces, classes, access control, inheritance, and function types.
Declaring variables in TypeScript
TypeScript lets us declare a variable’s type before using it.
Primitive types
let text: string = 'Hello World';
let decimal: number = 123;
let binary: number = 0b0101;
let octal: number = 0o7777;
let hexadecimal: number = 0xffff;
let large: bigint = 100n;
let enabled: boolean = false;
let token: symbol = Symbol();
Object types
Arrays can use either T[] or Array<T> syntax:
let words: string[] = ['hello', 'world'];
let moreWords: Array<string> = ['hello', 'world'];
A tuple fixes the number and types of its elements:
let pair: [string, number] = ['hello', 1];
An enum defines a named set of values:
enum Sex {
Male,
Female,
}
let value: Sex = Sex.Male;
Interfaces describe an object’s required shape:
interface Hero {
name: string;
readonly id: number;
attack(): void;
}
An interface can:
- Declare properties and method signatures without implementations.
- Extend another interface.
- Declare read-only properties.
Classes
TypeScript classes support:
- Instance properties and methods.
- Static properties and methods.
- Constructors and instantiation with
new. - Access modifiers such as
public,protected, andprivate. - Class inheritance.
- Interface implementation.
- Parameter properties, such as
constructor(private name: string) {}. - Arrow-function fields that preserve lexical
this. - Method overriding and overload signatures.
Function types
Function parameters and return values can be typed explicitly:
function add(left: number, right: number): number {
return left + right;
}
const format: (value: number) => string = (value) => String(value);
These examples form a starting point; modern TypeScript also adds unions, intersections, generics, conditional types, type inference, and many more tools for modeling application data.