본문 바로가기

Language/TypeScript18

타입 가드 ■ 타입 가드 function numOrStr(a: number | string) { a.toFixed(1); // [ERROR] string 형식에 toFixed 속성이 없음 // 타입 가드 if (typeof a === "number") { a.toFixed(1); } else { a.charAt(3); } } 타입스크립트는 배열도 구분 가능 function numOrNumArray(a: number | number[]) { // 배열 확인 조건식 if (Array.isArray(a)) { // number[] a.concat(4); } else { // number a.toFixed(3); } } 클래스도 타입이 될 수 있다. class A { aaa() {} } class B { bbb() {} .. 2023. 2. 16.
unknown, any ■ any interface A { talk: () => void; } const a: A = { talk() { return 3; }, }; // any의 문제점 : 타입 검사를 포기, 존재하지 않는 메소드의 호출이 가능해짐 const b: any = a.talk(); b.method(); // 존재하지 않는 메소드이지만 에러 표시 안됨 ■ unknown interface A { talk: () => void; } const a: A = { talk() { return 3; }, }; // unknown 사용시에는 타입을 사용자가 지정. 현재 타입을 모를 때 사용 const c: unknown = a.talk(); (c as A).talk(); unknown 대표 예시 try { } catch (err.. 2023. 2. 15.
void ■ 잉여 속성 검사 interface A { a: string; } const obj: A = { a: "hello", b: "world" }; // b 속성에 에러 발생 // 개체 리터럴에는 잉여 속성 검사가 존재 const obj1 = { a: "hello", b: "world" }; const obj2: A = obj1; // 에러 검사 오류 ■ void // 반환형이 void 이면 undefined return 가능 function a(): void { return "hello"; // ERROR } function b(): void { return null; // ERROR } function c(): void { return undefined; } ■ void 의 세가지 형식 function .. 2023. 2. 13.
타입과 인터페이스 상속 ■ 타입 상속 type Animal = { breath: true }; type Cat = Animal & { breed: true }; type Human = Cat & { think: true }; // type 에서 & 를 상속의 개념으로 사용 const lee: Human = { breath: true, breed: true, think: true }; ■ 인터페이스 상속 interface A { breath: true; } interface B extends A { breed: true; } // interface 에서는 extends 키워드를 사용하여 상속 const b: B = { breath: true, breed: true }; // type Human 을 extends 키워드를 이용하여.. 2023. 2. 11.