Interface

Example Code

Variable parameter interface

interface IsEngineer {
  name: string;
  age: number;
  coding(code: string): void;
}


const engineer: IsEngineer = {
  name: 'KJ',
  age: 18,
  coding(code: string): void {
    console.log(code);
  }
}

let someEngineer: IsEngineer;

Optional parameter interface

interface PaintOptions {
  shape: Shape;
  xPos?: number;
  yPos?: number;
}

function paintShape(opts: PaintOptions) {
  // ...
}

const shape = getShape();
paintShape({ shape });
paintShape({ shape, xPos: 100 });
paintShape({ shape, yPos: 100 });
paintShape({ shape, xPos: 100, yPos: 100 });

Function parameter interface

Before

function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}

After

function fn(parameterName: parameterType = defaultValue)

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

function greet(person: Person) {
  return "Hello " + person.name;
}

or

type Person = {
  name: string;
  age: number;
};

function greet(person: Person) {
  return "Hello " + person.name;
}

Reference