📒

6번 인터페이스 퀴즈

 

Q1. 다음 코드를 각각 타입 별칭과 인터페이스로 타입을 지정해보세요.

let divBox = { color:'red', width:100 }
 
💡
정답 타입 별칭과 인터페이스는 일반 변수와 차별화를 하기 위해서 관습적으로 대문자를 사용한다. 정답에서는 타입 별칭과 인터페이스의 이름을 Style로 사용했다. 1) 타입별칭 타입 지정 방법
type Style ={ color:string, width:number } let divBox : Style= { color:'red', width:100 }
2) 인터페이스 타입 지정 방법
interface Style{ color:string, width:number, } let divBox : Style= { color:'red', width:100 }

 

Q2. 다음 코드에서 어느 부분 때문에 에러가 발생하는지 고르고, 에러가 발생하는 이유에 대해 작성해보세요. ((a)-(e) 중 정답 2개)

interface Info{ name: string, //(a) age: number, //(b) weight:number, //(c) marriage: boolean, //(d) favoriteFood : string[] //(e) } let person:Info= { name: '선은혜', marriage :false, favoriteFood:['chicken','cake','pizza'] }
 
💡
정답: (b),(c) 변수 person은 인터페이스 Info라고 지정해주었으므로 Info가 가지고 있는 속성 개수를 일치시켜야한다. 따라서, 변수 person에는 age와 weight 가 들어가야한다. 혹은, Info인터페이스 부분에 age? :number , weight? :number 라고 옵션 속성을 표시해주어야한다.

 

Q3. 다음 코드에서 빈칸에 들어갈 수 없는 것을 모두 고르세요.

interface Taste { sweet: boolean; } interface Shape { color: string; } interface Apple extends Shape, Taste { length: number; } let apple = {} as Apple; /* 빈칸 */ apple.name = ''
1) apple.name = ‘Apple’;
2) apple.length = 20;
3) apple.sweet = 'No';
4) apple.color = ‘blue’;
5) apple[1] = ‘sale’;
 
💡
정답: 1, 3, 5 Apple interface 를 extends 키워드를 통해 확장했으므로 Apple , Taste, Shape interface 에 명시된 프로퍼티를 사용 가능하다.

 

Q4. 다음 중 문법적으로 틀린 것을 고르세요.

      interface Icecream { flavor: string; } interface Icecream { price: number; }
      interface CatFood = "Cheese" | "Tuna" | "Apple";
    1. type Phone = { size: string[], color: string; } type IPhone = Phone & { series: "iPhone13" | "iPhone14"; }
      interface Phone { size: string[], color: string; } interface IPhone extends Phone { series: "iPhone13" | "iPhone14"; }
 
💡
정답: b interface 로 지정할 타입에는 키 값이 필요하다. 원시형 데이터를 이용한 타입을 정의하는 경우에는 type 키워드를 사용해 타입 별칭으로 선언해야 한다.