티스토리 뷰

타입스크립트 Interface 코드 사용 예시

interface 키워드를 사용해 값이 특정한 형태(shape)를 갖도록 제약할 수 있다. 인터페이스를 정의하는 기본적인 문법은 객체 타입의 그것과 유사하다.

예제코드를 보면서 Interface의 활용법을 확인해보자.

 

@ 객체형Interface 

type Score ='A' | 'B' | 'C' | 'F';

interface User{
    name : string;
    age : number;
    gender? : string;
    readonly birthYear: number;
    [grade : number] : Score;
    // 키값을 배열형태로 받을 수 있다.
    // grade는 다른값으로 대체될 수 있음.
}

let user : User = {
    name : 'xx',
    age : 30,
    birthYear : 2000,
    // 배열 형태로 받은 키값을 아래와 같이 쓸 수 있다.
    1 : 'A',
    2 : 'B',
    3 : 'C',
    4 : 'F'
    
}

 

@ 함수형Interface 

// 인자의 형식과, return 값의 형식을 지정해준다.
interface Add {
    (num1 : number , num2 : number ): number;
}

const add : Add = function(x,y){
    return x+y;
}
    
add(10,20);  // 30

interface IsAdult {
    (age : number) : boolean;
}

const a : IsAdult = (age) => {
    return age > 19;
}


a(33); // true


@ Class형 Interface 

class Bmw implements Car {
    color;
    wheels = 4;
    // color를 입력받기 위함
    constructor(c:string){
        this.color = c;
    }
    start(){
        console.log('go..')
    }
}

const b = new Bmw('green');
console.log(b) 
b.start()

// 출력
// Bmw: {
//   "wheels": 4,
//   "color": "green"
// } 
// "go.."

 

@ Class형 Interface - extends를 이용한 확장

interface Car {
    color : string;
    wheels : number;
    start() : void;
}

interface Toy {
    name : string;
}

// 동시확장 가능
interface ToyCar extends Car, Toy {
    price : number; 
}

const myCar : ToyCar = {

	color : 'red',
    wheels : 5,
    start(){
    	console.log('출발')
    },
    name : 'bmw',
    price : 50000
}

 

 

 

댓글
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함