TypeScript_Interfaces

LOOPY·2021년 8월 18일
post-thumbnail
interface Person{
  name: string;
  age: number;
}

1. Optional property

  • property에 ? 붙이면 있어도 되고 없어도 된다는 의미 age?: number
  • indexable type: property에 [index: string]: any; 넣어두면 Person에 어떤 이름의 property가 와도 괜찮다

2. Function in interface

  • interface의 property로 함수 선언부 지정해두고 할당 시 정의하기
interface Person {
  name: string;
  age: number;
  hello(): void;
}

***
  
const p1: Person{
  name: ‘Mark’,
  age: 39,
  hello: function(): void{
    console.log(`hi ${this.name}`);
  }
}
  • function 키워드 없이 hello(): void { .. } 가능
  • 화살표함수로 hello: (): void => { .. } 가능 (이 때 this 사용 주의)

3. Class implements interface

  • interface로 class 구현
interface IPerson{
  name: string;
  age?: number;
  hello(): void;
}

class Person implements IPerson{
  name: string;
  age?: number | undefined;
  constructor(name: string){
    this.name = name;
  } 
  hello(): void{
    console.log(`hi ${this.name}`);
  }
}

const person: IPerson1 = new Person(‘Mark’);
person.hello();

4. Interface extends interface

  • interface를 상속(확장)하는 interface
  • interface Ikorean extends IPerson { .. }

5. Function interface

  • interface로 함수 만들기
interface HelloPerson{
  (name: string, age?: number): void;
}
const helloPerson: HelloPerson = function(name: string){
  console.log(`hi ${name}`);
}

6. Readonly Interface Properties

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

const p1: Person = { 
  name: ‘Mark’,
  gender: ‘male’,
}

p1.gender = ‘female’; // error
profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글