Introduction to TypeScript. Interfaces

작성자

카테고리:

← 피드로
DEV Community · Julia Shlykova · 2026-06-19 개발(SW)

Julia Shlykova

Basic syntax

We know that we can use object literals to specify what property types we can use. However, what if you have multiple objects with the same structure? Interface is a programming structure that allows to create types for objects.

interface Settings {
  color: string;
  delay: number;
  retry: boolean;
}

const mySettings: Settings = {
  color: "black",
  delay: 1000,
  retry: false
}

console.log(mySettings.color);

Enter fullscreen mode Exit fullscreen mode

Pay attention that when we define interface we use “semicolon”.

Optional property

We can define optional property using ?: symbols:

interface Settings {
  color: string;
  delay: number;
  retry?: boolean;
}

const mySettings: Settings = {
  color: "black",
  delay: 1000
}

console.log(mySettings.retry); //undefined

Enter fullscreen mode Exit fullscreen mode

Index signatures

Sometimes we don’t know how many properties an object will have. We can specify expected types:

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

const p: Person = {
  name: 'Mary',
  lastName: 'Smith'
}

p['age'] = 50; // Type 'number' is not assignable to type 'string'

Enter fullscreen mode Exit fullscreen mode

Methods

Of course, we should be able to define methods:

interface Settings {
  color: string;
  delay: number;
  describe: () => void;
}

const mySettings: Settings = {
  color: "black",
  delay: 1000,
  describe: function () {
    console.log("Your favorite color is " + this.color)
  }
}

console.log(mySettings.describe());

Enter fullscreen mode Exit fullscreen mode

Here, in interface, we defined type of describe as () => void, that means function. In this case void doesn’t indicate that a function mustn’t return any value, it indicates that it can return any value. The other way to set function type is : describe(): void.

Inheritance

Interfaces can inherit properties from another ones using extends:

interface Settings {
  color: string;
  delay: number;
  describe: () => void;
}

interface Game extends Settings{
  character: string;
}

const myGame: Game = {
  color: "black",
  delay: 1000,
  describe: function () {
    console.log("Your favorite color is " + this.color);
    return 'hi';
  },
  character: 'goat'
}

console.log(myGame.character); // goat

Enter fullscreen mode Exit fullscreen mode

Using as argument in function

interface Settings {
  color: string;
  delay: number;
}

function changeSettings(s: Settings): Settings {
  return {
    color: s.color,
    delay: s.delay + 1000
  }
}

Enter fullscreen mode Exit fullscreen mode

We specify what we expect the argument to be.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다