거꾸로 바라본 세상
반응형

인터페이스 구문

interface Book {
		//?를 이용한 선택적 속성(undefined 허용)
    author?: string;
    pages: number;
}

const ok: Book = {
    author: 'Devide',
    pages: 365
}

const missing: Book = {
    pages: 80
}

읽기전용 속성(readonly)

readonly는 interface에서만 사용

interface Page {
    readonly text: string;
}

function read(page: Page) {
    console.log(page.text);

    //Cannot assign to 'text' because it is a read-only property.
    page.text = '10';

함수와 메서드

  • 메서드 구문: 인터페이스 멤버를 member(): void와 같이 객체의 멤버로 호출되는 함수로 선언
  • 속성 구문: 인터페이스의 멤버를 member: () ⇒ void와 같이 독립 함수와 동일하게 선언
interface HasBothFunctinoTypes {
    property: () => string;
    method(): string;
}

const hasBoth: HasBothFunctinoTypes = {
    property: () => "",
    method() {
        return "";
    }
}

hasBoth.property();
hasBoth.method();

?키워드를 이용하여 필수로 제공하지 않아도 되는 멤버함수

interface OptionalReadonlyFunctions {
    optionalProperty?: () => string;
    optionalMethod?(): string;
}

중첩 인터페이스

객체 타입이 다른 객체 타입의 속성으로 중첩될 수 있는 것처럼 인터페이스 타입도 자체 인터페이스 타입 또는 객체 타입 속성으로 가질 수 있다.

interface Setting {
    place: string;
    year: number;
}

interface Novel {
    author: {
        name: string;
    }
    setting: Setting; //중첩인터페이스
}

let MyNovel: Novel;

MyNovel = {
    author: {
        name: 'hongil'
    },
    setting: {
        place: 'Seoul',
        year: 1812,
    }
}

console.log(MyNovel);

인터페이스 확장

extends 키워드를 통해 인터페이스를 확장하여 사용할 수 있다.

interface Writing {
    title: string;
}

interface Novella extends Writing {
    pages: number;
}

let myNovella: Novella = {
    pages: 195,
    title: 'Novalla'
}

console.log(myNovella);

다중 인터페이스 확장

extends 키워드 뒤에 여러개의 인터페이스를 추가할 수 있다.

interface Writing {
    title: string | null;
}
interface Reading {
    name: string
}
interface Novella extends Writing, Reading{
    pages: number;
    title: string;
}

let myNovella: Novella = {
    pages: 195,
    title: 'Novalla',
    name: 'paik'
}

console.log(myNovella);

인터페이스 속성 재정의(Override)

interface Writing {
    title: string | null;
}

interface Novella extends Writing {
    pages: number;
    title: string;
}

let myNovella: Novella = {
    pages: 195,
    title: 'Novalla'
}

console.log(myNovella);
반응형

'Language > TypeScript' 카테고리의 다른 글

[TypeScript] 함수, 배열  (0) 2023.08.07
[TypeScript] 타입시스템, 유니언과 리터럴  (0) 2023.08.07
profile

거꾸로 바라본 세상

@란지에。

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!