interface example1 - interface 기본

2woongjae/ts-basic-interface

/*
function hello1(person: { name: string; age: number; }): void {
    console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p1: { name: string; age: number; } = {
    name: 'Mark',
    age: 35
};

hello1(p1); // 안녕하세요! Mark 입니다.
*/

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

function hello1(person: Person1): void {
  console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p1: Person1 = {
  name: "Mark",
  age: 35
};

hello1(p1); // 안녕하세요! Mark 입니다.

interface example2 - optional property (1)

2woongjae/ts-basic-interface

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

function hello2(person: Person2): void {
  console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p21: Person2 = {
  name: 'Mark',
  age: 35
};

const p22: Person2 = {
  name: 'Anna'
};

hello2(p21); // 안녕하세요! Mark 입니다.
hello2(p22); // 안녕하세요! Anna 입니다.

interface example3 - optional property (2)

2woongjae/ts-basic-interface

interface Person3 {
  name: string;
  age?: number;
  [props: string]: any;
}

function hello3(person: Person3): void {
  console.log(`안녕하세요! ${person.name} 입니다.`);
}

const p31: Person3 = {
  name: 'Mark',
  age: 35
};

const p32: Person3 = {
  name: 'Anna',
  systers: ['Sung', 'Chan']
};

const p33: Person3 = {
  name: 'Bokdaengi',
  father: p31,
  mother: p32
};

hello3(p31); // 안녕하세요! Mark 입니다.
hello3(p32); // 안녕하세요! Anna 입니다.
hello3(p33); // 안녕하세요! Bokdaengi 입니다.

interface example4 - function in interface

2woongjae/ts-basic-interface

interface Person4 {
  name: string;
  age: number;
  hello(): void;
}

const p41: Person4 = {
  name: 'Mark',
  age: 35,
  hello: function(): void {
    console.log(this);
    console.log(`안녕하세요! ${this.name} 입니다.`);
  }
};

const p42: Person4 = {
  name: 'Mark',
  age: 35,
  hello(): void {
    console.log(this);
    console.log(`안녕하세요! ${this.name} 입니다.`);
  }
};

/*
const p43: Person4 = {
  name: 'Mark',
  age: 35,
  hello: (this: Person4): void => {
    console.log(this);
    console.log(`안녕하세요! ${this.name} 입니다.`);
  }
};
*/

p41.hello(); // 안녕하세요! Mark 입니다.
p42.hello(); // 안녕하세요! Mark 입니다.
// p43.hello(); // 안녕하세요! 입니다.

* noImplicitThis 의 중요성

--noImplicitThis

interface example5 - class implements interface

상속은 불가능!

2woongjae/ts-basic-interface

interface IPerson1 {
  name: string;
  age?: number;
  hello(): void;
}

class Person implements IPerson1 {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  hello(): void {
    console.log(`안녕하세요! ${this.name} 입니다.`);
  }
}

const person = new Person('Mark');
person.hello(); // 안녕하세요! Mark 입니다.

interface example6 - interface extends interface

2woongjae/ts-basic-interface