Language/Javascript·Typescript

[TypeScript/타입스크립트] 인터페이스(interface)

딜레이레이 2023. 3. 6. 18:27

[참고]

 

인터페이스 | 타입스크립트 핸드북

인터페이스 인터페이스는 상호 간에 정의한 약속 혹은 규칙을 의미합니다. 타입스크립트에서의 인터페이스는 보통 다음과 같은 범주에 대해 약속을 정의할 수 있습니다. 객체의 스펙(속성과 속

joshua1988.github.io

  • 프로퍼티(Property)를 정해서 객체를 사용하고자 할 때는 인터페이스(interface)를 사용.
interface User {
    name : string;
    age : number;
}

let user: User = {
    name : 'Alice',
    age : 20
}

// 프로퍼티 사용
console.log(user.name);	//Alice

옵션

  • 뒤에 물음표를 붙여주면 옵션으로 사용 가능. 
  • 아래의 예시에서처럼 age? 이렇게 써주면 옵션으로 사용할 수 있다. 객체를 생성 시 age는 넣어주지 않아도 된다. 꼭 있어야하는 속성은 아니라는 말이다.
interface User {
    name : string;
    age? : number;
}

 

 

읽기 전용 속성

  • 인터페이스로 객체를 처음 생성할 때만 값을 할당하고 그 이후에는 값을 변경할 수 없는 속성.
  • 앞에 readonly를 붙인다.
interface User {
    readonly name : string;
    age? : number;
}
  • 인터페이스로 객체 생성 후 수정하려 하면 오류 발생
let alice : User = {
    name : 'Alice',
    grade : 'GOLD'
}

alice.name = 'Bob';	// Error!!

 

읽기 전용 배열

  • 배열 선언 시 ReadonlyArray<T> 타입을 사용하면 읽기하면 읽기 전용 배열 생성 가능.
let arr: ReadonlyArray<number> = [1,2,3];
arr.splice(0,1); // Error!!
arr.push(4); // Error!!
arr[0] = 100; // Error!!

 

 

정의하지 않은 속성들 사용

  • 아래와 같이 속성을 정의하면 string으로 들어온 속성들의 타입은 number이면 된다는 말이다.
    즉, key 값은 string, value 값은 number인 속성을 넣을 수 있다는 뜻. 이름은 prop이든 다른거든 아무거나 상관없다.
interface User {
    age? : number;
    [prop: string] : number;
}

 

인터페이스로 함수 정의

  • 인터페이스에 아래와 같이 함수 정의 가능
  • 괄호 안의 값은 파라미터, 그리고 콜론(:) 오른쪽의 값은 리턴 타입.
interface Add {
    (num1:number, num2:number): number;
}

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

add(10, 20);

 

인터페이스로 클래스 정의

  • implements 키워드는 class의 interface에 만족하는지 여부를 체크할 때 사용된다. 
  • interface로 정의한 값들은 모두 필수적으로 들어가야 하며, 하나라도 빠질 경우 에러를 반환한다.
// 클래스 정의
interface Car {
    color: string;
    wheels: number;
    start(): void;
}

class Bmw implements Car {
    color;
    wheels = 4;
    constructor(c:string){
        this.color = c;
    }

    start(): void {
        console.log("Go!!");
    }
}

const b = new Bmw("green");
console.log(b); // Bmw { wheels: 4, color: 'green' }
b.start();  // Go!!

 

인터페이스 확장

  • 클래스와 마찬가지로 인터페이스도 확장 가능.
  • 인터페이스 정의 시 뒤에 extends + 상속받을 인터페이스를 붙여줌.
interface Car {
    color: string;
    wheels: number;
    start(): void;
}

// 인터페이스 확장
interface Benz extends Car {
    doors: number;
    stop(): void;
}

const benz: Benz = {
    color :"black",
    wheels : 4,
    doors : 4,
    start(){
        console.log("Go!!");
    },
    stop(){
        console.log("Stop!!");
    }
}

console.log(benz);
/*
{
    color: 'black',
    wheels: 4,
    doors: 4,
    start: [Function: start],
    stop: [Function: stop]
  }
*/
benz.start();   // Go!!
benz.stop();    // Stop!!
  • 인터페이스 2개 동시에 확장도 가능
interface Car {
    color: string;
    wheels: number;
    start(): void;
}

interface Toy {
    name: string;
}

interface ToyCar extends Car, Toy {
    price: number;
}