TypeScript 인터페이스 스터디

dev.horang🐯·2023년 3월 7일
0
//인터페이스 : 미리 타입 지정해서 함수에 들어오는 props 값을 지정해 줄 수 있음
interface LabeledValue {
    label: string;
}

function printLabel(labeledObj: LabeledValue) {
    console.log(labeledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

//타입 검사는 순서는 상관 없고 존재여부와 충족여부만 파악한다

//선택적 프로퍼티 : 옵셔널 체이닝 -> 들어오지 않을 수도 있는 변수와 들어올 시에 지정될 타입을 미리 설정해준다.
interface SquareConfig {
    color?: string;
    width?: number;
}

//읽기 전용 프로퍼티 : 생성될때만 수정 가능. 할당 이후에 값 변경 불가 const 느낌..? 
interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // 오류!
//배열 생성후 값 변경 불가
let ro: ReadonlyArray<number> = a;

//초과 프로퍼티 검사 : 이미 인터페이스로 지정해둔 프로퍼티 이외의 프로퍼티가 들어오게 되면 타입 스크립트의 경우 이를 오류로 인지하고 에러를 뱉음 이 과정을 피하기 위해서 타입 단언을 사용한다.
// error: Object literal may only specify known properties, but 'colour' does not exist in type 'SquareConfig'. Did you mean to write 'color'?
let mySquare = createSquare({ colour: "red", width: 100 });

//1.타입 단언
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
// opacity 프로퍼티를 추가로 집어 넣었음
// 2. 어차피 추가 프로퍼티는 들어올거야 라고 확신한다면 인터페이스에서 
interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any;
}
//이렇게 지정해줄 수있다. (인덱스 서명)
//3. 객체를 다른 변수에 할당한다. 추가 프로퍼티 검사를 받지 않음(왜?)
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
//단 squareOptions와 SquareConfig 사이에 공통 프로퍼티가 있는 경우에만 사용 가능하다.(위 예제의 경우 width 프로퍼티가 공통으로 들어있음)

//함수 타입
interface SearchFunc {
    (source: string, subString: string): boolean;
}
//매개변수 값이 같을 필요는 없다.
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string): boolean {
    let result = src.search(sub);
    return result > -1;
}
//만일 리턴값이 인터페이스에서 정한 타입과 다르다면 오류를 뱉는다.

//인덱서블 타입 : 타입을 인덱스로 사용 -> 문자열과 숫자만 사용가능
interface StringArray {
    [index: number]: string;
}

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

let myStr: string = myArray[0];

//프로퍼티 값을 허용
interface NumberOrStringDictionary {
    [index: string]: number | string;
    length: number;    // 성공, length는 숫자입니다
    name: string;      // 성공, name은 문자열입니다
}

//클래스 타입
interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}
//클래스 타입 1 : 스테틱 타입



//인터페이스 확장 : 얜 왜하는거야? 처음부터 Shape 만들때 sideLength 넣어 사용하면 되는거아닌가
//한 인터페이스의 멤버를 재사용성 높은 컴포로 쪼갤때 유용
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

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

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

//하이브리드타입

profile
좋아하는걸 배우는건 신나🎵

0개의 댓글