Interface_TypeScript

miin·2022년 9월 26일
0

TypeScript

목록 보기
4/9
post-thumbnail

예시

  • 기본, 형태만 똑같으면 된다
interface AppValue{
  label: string;
}

function printLabel(labeledObj: AppValue) {
    console.log(labeledObj.label);
}
  • 선택적 프로퍼티
interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
....
}
  • 확장하기
    한 인터페이스의 멤버를 다른 인터페이스에 복사하는 것을 가능하게 해준다.
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape {
    sideLength: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
  • 읽기전용 프로퍼티, 객체가 처음 생성될 때만 수정 가능할 때 사용
interface Point {
    readonly x: number;
    readonly y: number;
}
  • 함수타입
interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1;
}
  • 인덱서블 타입
    타입을 인덱스로 기술할 수 있다
interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

0개의 댓글