자바에서 다루는 Interface와 비슷하다.

Interface 없는 예제

const person: { name: string, age: number } = {
  name: 'max',
  age: 30,
};

Interface 사용

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: 'max',
  age: 30,
};

함수에서도 사용

interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: 'max',
  age: 30,
};

function hello(someone: Person): void {
  console.log(`Hello ${someone.name}, ${someone.age}`);
}

hello(person);

Optional한 프로퍼티

interface Person {
  name: string;
  age?: number;
}

Indexable type

Optional한 타입 때문에 생긴건 아니지만 비슷하게 쓸 수 있다.

interface Person {
  name: string;
  [key: string]: string;
}

const person: Person = {
  name: 'max',
};

person.anybody = 'anna';
person.anybody2 = 'anna2';

function hello(someone: Person): void {
  console.log(`Hello ${someone.name}, ${someone.age}, ${someone.anybody}`);
}

hello(person);