[TS] TypeScript - Interface

Janet·2023년 1월 16일
0

TypeScript

목록 보기
4/8

🔷 Interface란?

  • Interface는 TypeScript에서 타입 체크를 위해 사용된다. 여러가지의 타입을 갖는 property로 이루어져, 일종의 새로운 타입의 정의를 하는 것이다.
  • 변수, 클래스, 함수 등에 사용할 수 있다.

🔷 Interface 예제

// =====Interface=====
// #1. Interface 기본 예제
interface UserInfo {
  name : string;
  age : number;
  gender : string;
  address? : string;
  readonly birthYear : number;
  [grade :number] : string; //number를 받는 grade라는 key와 string을 받는 value의 array
}

let userInfo : UserInfo = {
  name : "xx",
  age : 20,
  birthYear : 2000,
  1 : "A", //[grade :number] : string;
  2 : "B"
}

userInfo.age = 10; //가능
userInfo.gender = "male"; //❌ interface엔 있어도 userInfo변수에 해당 항목 없기에
userInfo.address = "seoul"; //가능: Option 속성 "?"를 주었기 때문에
userInfo.birthYear = 1990; //❌ interface 해당 속성에 readonly속성을 줘서 수정 불가

//#2. interface를 함수에 사용하기
//interface로 함수의 parameter와 return값의 타입을 지정
//예제 1)
interface Add {
  (num1 :number, num2 :number) :number;
};

const add :Add = function(x, y) {
  return x + y;
};

add(10,20); //30

//예제 2)
interface IsAdult {
  (age :number) :boolean;
};

const userAge :IsAdult = (age) => {
  return age > 19;
};

userAge(30); //true
userAge(10); //false

//#3. Interface를 Class에 사용하기
//인터페이스에 class를 정의할때 'implements'키워드를 사용한다.
//예제 1)
interface Car {
  color : string;
  wheels : number;
  start() : void;
};

class Bmw implements Car {
  color = "red";
  wheels = 4;
  start() {
    console.log("go!");
  };
};

//예제 2) constructor 사용한 예제
class Volkswagen implements Car {
  color;
  wheels = 4;
  constructor(c : string) {
    this.color = c;
  };
  start() {
    console.log("go!");
  };
};

const volkswagen = new Volkswagen("blue");
console.log(volkswagen);

// #4. Interface는 확장(extends)이 가능하다.
//예제 1)
interface Fruits {
  color : string;
  price : number;
};

interface Mango extends Fruits {
  origin : string;
};

const mango :Mango = {
  color : "yellow",
  price : 2000,
  origin : "Thailand";
};

//여러 개 확장도 가능
interface Vegetables {
  color : string;
};

interface Food extends Fruits, Vegetables {
  name : string;
};
profile
😸

0개의 댓글