본문 바로가기
TypeScript

[TypeScript] implements 키워드

by 딩박사 2023. 10. 31.
반응형

* 본 포스팅은 필자가 개인적으로 학습한 내용정리 및 리뷰를 위해 포스팅합니다.


앞에서 배운 interface는 object 타입지정할 외 하나의 용도가 있는데
바로 class의 타입을 확인하고자 할 때
interfaceimplements를 활용한다.


class User {
    name : string;
    age : number = 27;
    constructor(a :string) {
    	this.name = a
    }
}

let user = new User('hoo');

▲ class User로 부터 생성되는 object들은 name과 age의 속성을 가지게 된다.

class가 name, age 속성을 가지고 있는지 타입으로 확인하려면 interface + implements 키워드로 확인한다!!

 

 

 

interface UserType {
    name : string,
    age : number
}

class User implements UserType {
    name : string;
    age : number = 27;
    constructor(a :string) {
    	this.name = a
    }
}

let user = new User('hoo');

▲ class 명 우측에 implements를 쓰고 interface명을 쓰면 '이 class가 이 interface에 있는 속성을 다 가지고 있는가?' 라고

확인이 가능하다. 빠진 속성이 있다면 에러로 알려준다.

 

 


 

implements는 타입지정문법이 아니다!!!
implements라는 것은 interface에 들어있는 속성을 가지고 있는지 확인만 하라는 뜻이다.
class에 타입을 할당하고 변형시키는 키워드는 결코 아니다 XXX

 

interface UserType {
    name : string,
    sum : (age :number) => number
}

class User implements UserType {
    name;		// any 타입이 된다.
    sum (a) {	// a 파라미터 any 타입이 된다.
    	return a + 1
    }
}

▲ UserType에 있던 name : string이 반영되는 것은 아니다. class안에서의 name은 any 타입이 된다. class 함수도 마찬가지로 함수에 있던 number 타입이 전혀 반영되지 않았다.

 

 

 

 

결론

implements는 interface와 함께 class의 타입을 체크하는 용도지 할당하거나 변경의 용도는 절대절대 아니다!

 

반응형

댓글