interface 와 type의 차이 TIL

이명진·2022년 6월 9일
0

typescript 공부

목록 보기
2/3

니꼬의 타입스크립트 강좌를 보고 정리한 내용이다.

interface

추상클래스는 다른 클래스가 가져야 할 property랑 메소드를 명시할수 있도록 도와준다.

abstract class User(){
constructor(
	protected firstName:string,
	protected lastName:string,){}
	abstract sayHi(name:string):string
	abstract fullName():string
}
class Player extends User{
}

extends 로 상속

청사진만 가능하지 new User() 는 불가능하다.

추상 클래스 abstract 는 기본 자바스크립트에서 없는 기능이다.
그래서 자바에서는 class User로 나타나는데

인터페이스는 컴파일하면 JS로 바뀌지 않고 사라지기 때문에 인터페이스를 사용하면 가볍게 사용이 가능하다.


interface User {
	firstName:string,
	lastName:string,
	sayHi(name:string):string,
	fullName():string
}

class Player implements User{
}

implements로 interface는 상속이 가능하다.

컴파일 하면

class player {} 만 남는다.

파일사이즈를 줄일수 있다. 클래스의 청사진을 그릴때 interface가 더 유리하다.

또한 interface로 만든 것을 동시에 상속하게 만들수 있다.

interface Humun{
	health:number
}

라고 지정하면
class Player implements User,Humun {} 으로 동시 상속이 가능하다

함수의 매개변수의 타입, 리턴 타입으로 인터페이스를 지정 가능하다.

function fx(user: User):User{}

interface와 type 정리

모양

type

type name ={ } 객체 형태 , type name = number 타입을 지정, type number = 1 | 2 값을 지정해서 사용할수 있다.

인터페이스

interface name {
name:string
}
으로 객체 형태로 쓴다 .

사용은 둘다 같다. 타입을 지정할때 사용한다.
const player : name = {}

상속

type name2 = name & { 원하는 형태 }

interface name2 extends name { 원하는 형태 }

type 은 중복이 안되지만 interface는 중복이 된다.

interface name {bb:string }
기존의 name에 합쳐진다.

type이나 interface 나 클래스에 상속이 가능하다 .

class User implements (type,interface) {} 이렇게 써도 된다.

profile
프론트엔드 개발자 초보에서 고수까지!

0개의 댓글