TypeScript - Interface(인터페이스)

oong·2022년 8월 10일
0

인터페이스는 일반적으로 타입 체크를 위해 사용되며 변수, 함수, 클래스에 사용할 수 있다. 인터페이스는 여러가지 타입을 갖는 프로퍼티로 이루어진 새로운 타입을 정의하는 것과 유사하다. 인터페이스에 선언된 프로퍼티 또는 메소드의 구현을 강제하여 일관성을 유지할 수 있도록 하는 것이다. ES6는 인터페이스를 지원하지 않지만 TypeScript는 인터페이스를 지원한다.인터페이스는 프로퍼티와 메소드를 가질 수 있다는 점에서 클래스와 유사하나 직접 인스턴스를 생성할 수 없고 모든 메소드는 추상 메소드이다. 단, 추상 클래스의 추상 메소드와 달리 abstract 키워드를 사용하지 않는다.

type Score = 'A' | 'B' | 'C' | 'F';

interface User {
  name: string;
  age: number;
  gerder?: string; // 속성명 뒤에 ?를 붙이면 값이 비어있어도 괜찮다는 뜻이다. (optional property)
  readonly birthYear: number; // readonly는 값을 읽게만 할 수 있다. 값 변경 불가능
  [grade:number]: Score; //number를 key로 받고 Score을 value로 받는 프로퍼티를 여러 개 가져올 수 있다.
  
  let user : User = {
    name: 'Min Ji',
    age: 26,
    1: 'A',
    2: 'B',
}

interface로 함수 정의하기

// x + y 함수
interface Add {
  (num1:number, num2:number): number;
}

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

// 나이가 성인인지 여부 함수
interface IsAdult {
    (age:number):boolean;
}

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

interface로 클래스 정의하기

interface Car {
    color: string;
    wheels: number;
    start(): void;
}

class Bmw implements Car {
    color;
    wheels = 4;
    constructor(c:string) {
        this.color = c;
    }
    start() {
        console.log('gogo');
    }
}

const b = new Bmw('green');

interface 확장 - extends

interface Car {
    color: string;
    wheels: number;
    start(): void;
}

interface Benz extends Car {
    door: number;
    stop(): void;
}

// extends는 여러개를 할 수 있다.
interface Toy {
  name: string;
}

interface ToyCar extends Car, Toy {
  price: number;

0개의 댓글

관련 채용 정보