Interfaces
An interface describes the shape an object must have: which properties it has and of what type.
interface User {
name: string;
age: number;
active?: boolean; // ? = optional property
}
const ana: User = { name: "Ana", age: 30 };
If ana were missing name or had an extra undeclared property,
TypeScript would warn you.
Function types
You can annotate the parameters and the return value of a function.
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string): string => `Hello, ${name}`;
If a function returns nothing, its return type is void:
function log(message: string): void {
console.log(message);
}
The logic of these functions is regular JavaScript. The only thing TS adds are the annotations
: number,: string, etc.
Examples
The function in plain JS (without annotations)
function add(a, b) {
return a + b;
}
const greet = (name) => "Hello, " + name;
console.log(add(2, 3));
console.log(greet("Ana"));