본문 바로가기

끄적끄적

typescript interface

내가 공부하기 위해 기록.

  • interface 만들 때 대문자로 보통 시작.
type Square = {color:string, width:number} //1.이것도 가능하다.

//2. object 타입 지정 시 interface 사용가능
interface Square {color:string, width:number}

let 네모 = {
  color: 'red',
  width:100
}

typeAlias와 쓰는 법은 비슷하다.

다른 점? 중복 선언 가능/불가능

//interface 는 중복 선언 가능 
interface Student {name: string}
interface Student {score: number}


//type은 중복 선언 불가능

즉, 동일한 이름으로 중복선언이 가능하고 Student = {name:string,score:number}가 된다.

=> 나중에 추가할 타입이 많아질 경우라면 interface를 사용하는게 낫겠다. => 커스팅마이징 쉬움


interface 장점)

extends로 복사 가능 : 같은 속성을 복사하듯이 가져올 수 있다.

interface Apple {name:string}
interface Orange extends Apple {price:number}

let 사과:Student = {color:'red'}
let 귤:Teacher = {color:'orange', price:2000}

Orange 타입에 Apple을 가져와서 price속성을 추가할 수 있다.

 

그럼 typeAlias는?)

typeAlias는 extends 대신 ' & ' 기호로 가져올 수 있다. 

type Animal ={name:string}
type Cat = {age:number} & Animal  //animal타입을 &기호로 가져올 수 있다.

//즉, Cat객체에 타입을 지정할때는 저 두 가지의 속성을 다 만족해야된다.

extends 사용 중 중복이 발생하면? =>미리 에러를 발생시켜 잡아준다

& 의 경우 미리 발생시키지 않으므로 조금 더 주의해서 사용해줘야한다.

 

 

'끄적끄적' 카테고리의 다른 글

Redux의 상태관리의 주요 개념, 상태관리 비교  (0) 2023.04.25
React memoization  (0) 2023.04.23
좋은 TIL은 뭘까?(38)  (1) 2022.12.22
CSS-flex  (0) 2022.11.16
4주차 부족한부분 공부  (0) 2022.10.28