카테고리 없음
Typescript #3 인터페이스(interface)
nh_3521099031483
2024. 5. 3. 17:09
타입스크립트 인터페이스에 대해 알아보자.
let user:object;
user = {
name: 'xx',
age: 30
}
console.log(user.name) // user의 name을 찍어보면 에러가 발생한다. 오브젝트에는 특정 속성값의 정보가 없기 때문이다.
// 이렇게 프로퍼티를 정의해서 객체로 표현하고자 할 때는 인터페이스를 사용한다.
// 1. 인터페이스 사용 예제
type Score = 'A'|'B'|'C'|'F'; // 타입을 만들어서 지정할 수 있다.
interface User {
name : string;
age : number;
gender? : string; // 있어도 되고 없어도 되는 옵셔널한 프로퍼티이다. ? 사용
readonly birthYear : number;
[grade:number] : Score; // number를 key로 하고 Score를 value로 하는 프로퍼티를 여러개 나둘 수 있다는 것 이다.
}
let user2 : User = {
name : 'xx',
age : 30,
birthYear : 2000,
1 : 'A',
2 : 'B'
}
console.log(user2.age) // 에러가 발생하지 않는다.
user2.age = 10; // 재할당을 하는 것도 에러가 없다.
user2.gender = 'male'; // 옵셔널한 요소이므로 할당이 가능하다.
user.birthYear = 1990; // 읽기 전용이므로 에러가 난다.
// 2. 인터페이스로 함수 정의하기 예제
interface Add {
(num1:number, num2:number): number;
}
const add : Add = function(x, y){ // 인터페이스에선 num1, num2로 설정했지만 x, y로 사용해도 되는 모습
return x + y;
}
add(10, 20);
add(10, 20, 30); // 하나 더 값이 들어가면 에러가 발생
add(10,"20"); // 타입이 다른게 들어가면 에러가 발생
interface IsAdult {
(age:number):boolean;
}
const a:IsAdult = (age) => {
return age > 19;
}
a(33) // true
// 3. 인터페이스로 클래스 정의하기 예제
interface Car {
color: string;
wheels: number;
start(): void;
}
class Bmw implements Car {
// 인터페이스에 있는 속성 값을 모두 입력해야 한다.
color;
wheels = 4;
constructor(c:string){
this.color = c;
}
start(){
console.log('go...');
}
}
const b = new Bmw('green'); // constructor 사용
console.log(b) // Bmw: {"wheels": 4, "color": "green"}
b.start(); // "go..."
// 4. 인터페이스 확장하기 extends 예제
interface Benz extends Car {
door: number;
stop(): void;
}
const benz : Benz = {
door : 5,
stop(){
console.log('stop..');
},
color : 'black',
wheels: 4,
start(){
console.log('go...')
}
}
// 5. 확장 여러개 하기
interface Car1 {
color: string;
wheels: number;
start(): void;
}
interface Toy {
name: string;
}
interface ToyCar extends Car1, Toy {
price : number;
}