TypeScript interface

최진서·2023년 2월 16일
0

선택적 프로퍼티(Optional Properties)

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
    let newSquare = {color: "white", area: 100};
    if (config.clor) {
        // Error: Property 'clor' does not exist on type 'SquareConfig'
        newSquare.color = config.clor;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: "black"});

createSquare안의 color 프로퍼티 이름을 잘못 입력하면, 오류 메시지로 알려줌

읽기전용 프로퍼티(Readonly properties)

interface Point {
    readonly x: number;
    readonly y: number;
}

Point의 x,y의 값이 할당되면 수정 불가

함수 타입(Function Types)

interface SearchFunc {
    (source: string, subString: string): boolean;
}

한번 정의하면 함수 타입 인터페이스는 다른 인터페이스처럼 사용할 수 있음

let mySearch: SearchFunc;
mySearch = function(src, sub) {
    let result = src.search(sub);
    return result > -1;
}

true or false로 반환값이 나옴

참고자료

https://typescript-kr.github.io/pages/interfaces.html

profile
Frontend developer

0개의 댓글