DevPath · Learn to code ESPTEN

Introduction to TypeScript

Interfaces and function types

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"));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Why types and basic typesGenerics and unions →