TypeScript adds static types on top of JavaScript. A variable can be given an explicit type with a colon, and if the type is not specified — the compiler infers it from the value (inference). On a type mismatch, tsc reports an error even before launch.
- Catch type errors at compile time, not at runtime.
- Make the intent of the code explicit: it is clear what type a function expects.
let age: number = 25
console.log(typeof age)Output:
numberThe colon sets the type of the variable. number here matches the JS type of the value.
const score = 100
console.log(typeof score)Output:
numberWithout an annotation TypeScript infers the score type = number from the value 100.
const nums: number[] = [1, 2, 3]
console.log(nums.length)Output:
3number[] — an array where every element must be a number.
Key rules:
- ✓An annotation goes after the name: let x: number.
- ✓If the type is not set, TypeScript infers it from the value.
- ✓T[] — an array of elements of type T.
Common mistakes:
- !You cannot assign a value of an incompatible type — it will be a compile error.
- !any disables type checking; it is usually avoided.
An interface describes the shape of an object: which properties are required and what types they have. An object declared with an interface type must contain all required fields; ? makes a property optional, readonly — immutable.
- Type data structures and function parameters.
- Define a contract: what fields we expect on an object.
interface User {
name: string
age: number
}
const u: User = { name: 'Anna', age: 21 }
console.log(u.age)Output:
21The u object must contain name: string and age: number — otherwise the compiler will point out the error.
interface Config {
title: string
theme?: string
}
const c: Config = { title: 'Site' }
console.log(c.theme)Output:
undefinedtheme? — an optional field: it can be omitted, then the value is undefined.
interface Point {
readonly x: number
y: number
}
const p: Point = { x: 1, y: 2 }
p.x = 10Output:
Compile errorreadonly x cannot be overwritten — the assignment p.x = 10 causes an error at build time.
type ID = string | number
let id: ID = 42
console.log(typeof id)Output:
numbertype ID is a union alias: the variable can hold either a string or a number.
Key rules:
- ✓An interface defines the required properties and their types.
- ✓name? — the property is optional; its default is undefined.
- ✓readonly forbids overwriting a property.
Common mistakes:
- !Omitting a required property — a compile error.
- !Use type for unions and interface for object shapes.
A function has both parameters and the return value typed. If a function returns nothing, the return type is void. Parameters can have default values, and generics let you write functions that work with any type.
- Ensure type-safe calls: arguments are checked by the compiler.
- Reuse logic with different types via generics.
function add(a: number, b: number): number {
return a + b
}
console.log(add(2, 3))Output:
5a and b must be numbers, and return must return a number — the types are checked at build time.
function log(msg: string): void {
console.log(msg)
}
log('Hello')Output:
Hellovoid means the function returns nothing (implicitly returns undefined).
function greet(name: string = 'Guest') {
return 'Hello, ' + name
}
console.log(greet())Output:
Hello, GuestIf the argument is not passed, the default value is used; the parameter type is still string.
function identity<T>(value: T): T {
return value
}
const r = identity('hi')
console.log(typeof r)Output:
stringT is a type parameter: whatever type is passed, that type is returned, so the type of r is inferred as string.
Key rules:
- ✓Parameters and the result are typed explicitly; a mismatch is an error.
- ✓Functions without a result return void.
- ✓Generics <T> reuse logic with an arbitrary type.
Common mistakes:
- !Passing an argument of the wrong type — a compile error.
- !A generic without an inferred T falls back to unknown if the type is not defined.
In strict mode (strictNullChecks), null and undefined are separate types, and they cannot silently be assigned to number or string. Optional chaining ?. safely accesses a nested property and returns undefined if the value is empty. unknown means “the type is not known yet” and requires a check before use, unlike any which disables the check.
- Safely access nested fields that may be absent.
- Distinguish “unknown type” (unknown) from “unchecked type” (any).
type User = { name: string; nickname?: string }
const u: User = { name: 'Anna' }
console.log(u.nickname?.toUpperCase())Output:
undefinednickname is absent, so ?. throws no error and immediately returns undefined.
type User = { name: string; nickname?: string }
const u: User = { name: 'Anna', nickname: 'anna' }
console.log(u.nickname?.toUpperCase())Output:
ANNAIf nickname exists, ?. accesses it, and toUpperCase turns the string into "ANNA".
let age: number = nullOutput:
Compile errorIn strict mode null cannot be assigned to a variable of type number — it is a separate type.
let value: unknown = 42
const n: number = valueOutput:
Compile errorunknown cannot be directly assigned to number: the type must first be checked/narrowed. any would allow it.
Key rules:
- ✓null and undefined are separate types; direct assignment is an error.
- ✓?. returns undefined for an empty value without throwing.
- ✓unknown requires narrowing; any disables the check.
Common mistakes:
- !A forgotten ?. — reading a property of undefined throws a runtime error.
- !Confusing unknown and any is dangerous: unknown forces narrowing and is safer.
Functions are passed as values, and their type is set with the syntax (parameters) => return. Such a function type types callbacks — in array methods (map, filter) and in the parameters of other functions.
- Type callbacks passed to array methods and to your own functions.
- Describe handlers readably: what arguments a function expects and what it returns.
type Handler = (msg: string) => void
const log: Handler = (msg) => console.log(msg)
log('ok')Output:
okHandler — a function that takes a string and returns nothing (void); log matches it.
const nums: number[] = [1, 2, 3]
const doubled = nums.map((n: number) => n * 2)
console.log(doubled)Output:
[ 2, 4, 6 ]The elements are number[], so the map callback receives and returns numbers: each is multiplied by 2.
function repeat(msg: string, times: number, cb: (s: string) => void) {
for (let i = 0; i < times; i++) cb(msg)
}
repeat('beep', 2, (s) => console.log(s))Output:
beep
beepcb has the type (s: string) => void — a function taking a string; it is called once per iteration.
const nums: number[] = [1, 2, 3, 4]
const evens = nums.filter((n: number) => n % 2 === 0)
console.log(evens)Output:
[ 2, 4 ]The filter callback takes a number and returns a boolean — it decides whether to keep an element.
Key rules:
- ✓A function type is (arguments) => return.
- ✓Callbacks are typed as function parameters.
- ✓map/filter take the element type from the array generic — an annotation is often unnecessary.
Common mistakes:
- !A callback type mismatch — a compile error.
- !An arrow with a body without return returns undefined — important when a value is expected.