✊ 필오의 개발일지
Back to Posts
2017년 11월 27일

11/ Type Inference

11/ Type Inference

타입스크립트 정리 글은 이웅재님의 강의 강의록 을 참고하여 작성하였습니다. (짱짱) 오류가 있다면 언제든지 댓글 부탁드립니다.


1. 타입추론


2. 배열 타입 추론

const array1 = []; const array2 = ['a', 'b', 'c']; const array3 = ['a', 1, false]; // 타입이 다를 경우 union타입으로 추론된다. class Animal { name: string; } class Dog extends Animal { dog: string; } class Cat extends Animal { cat: string; } const array4 = [new Dog(), new Cat()];

3. 리턴 타입 추론

function hello(message: string | number) { if (message === 'world') { return 'world'; } else { return 0; } }

리터럴타입의 ‘world’이거나 0이 나온다.


4. 유니온 타입과 타입 가드

타입가드 Type guard

어떤 Scope에서 타입을 보증하는 런타임 체크를 수행하는 몇 가지 표현식이다. 타입 가드를 정의하기 위해서, 리턴 타입이 Type predicate인 함수를 정의 할 필요가 있다.

Type predicate

parameterName is Type
interface Person { name: string; age: number; } interface Car { brand: string; wheel: number; } function isPerson(arg: any): arg is Person { return arg.name !== undefined; } function hello(arg: Person | Car) { if (isPerson(arg)) { console.log(arg.name); // console.log(arg.brand); } else { // console.log(arg.name); console.log(arg.brand); } }

참고링크

  1. https://infoscis.github.io/2017/06/19/TypeScript-handbook-advanced-types/ 
PreviousReact에 typeScript 셋팅하기
Next10/ Decorator

Related

© 2025 Felix