타입스크립트는 타입을 추론할 때 단순히 값만 고려하지 않는다고 한다. 값이 존재하는 곳의 Context까지 고려한다고 함. Context까지 고려하는 타입스크립트의 타입 추론 때문에 가끔 직관적으로 이해하기 어려운 추론 결과가 나타나곤 한다. 이와 같이 Context를 고려한 타입추론 동작이 어떻게 돌아가는지 이해한다면 도움이 될 것이다.
type Pet = 'cat' | 'dog' | 'rat';
function printPet(pet: Pet){
console.log(pet);
}
printPet('cat') // 정상
//타입 추론은 변수의 할당 시점에 결정된다.
let cat = 'cat'; // 타입이 string
printPet(cat); // 비정상) string은 Pet 타입에 할당 불가.
let dog: Pet = 'dog'; //타입 선언에서 할당 가능한 값을 제한.
printPet(dog); // 정상
const rat = 'rat' // const를 사용하면 보다 구체적으로 타입을 추론함 타입이 'rat'
printPet(rat); //정상
|
[튜플 사용시 주의점]
function printCoord(coord: readonly [number, number]){
console.log(coord);
}
printCoord([10, 20]); // 정상
const coord = [10, 20]; // 타입이 number[]
printCoord(coord) // 비정상) coord의 길이는 언제든지 바뀔수 있음.
const coord_fix: [number, number] = [10, 20];
printCoord(coord_fix) // 정상)
const coord_fix2 = [10, 20] as const;
printCoord(coord_fix2); // 정상
|
[객체 사용시 주의점]
type Pet = 'cat' | 'dog' | 'rat';
interface OwnedPet {
owner: string,
pet_type: Pet,
}
function printOwnedPet(pet: OwnedPet){
console.log(pet);
}
const pet = {
owner : 'Peter',
pet_type: 'dog' // 타입이 string
}
printOwnedPet(pet); // 오류 'pet_type' 의 타입은 string임. string은 Pet에 할당 불가.
const pet2:OwnedPet = {
owner : 'Tommas',
pet_type: 'rat' // 타입이 Pet
}
printOwnedPet(pet2); // 정상
|
[콜백 사용시 주의점]
function callWithRandNum(fn: (n1: number, n2: number) => void){
fn(Math.random(), Math.random());
}
callWithRandNum((a, b)=>{ // 파라메터가 a: number, b: number가 타입 추론됨.
console.log(a + b);
}) // 정상
const callback = (a:number, b:number) => { // 파라메터의 타입 추론이 안되므로 명시적으로 타입을 기입해야함.
console.log(a + b);
}
callWithRandNum(callback) // 정상
|
'IT' 카테고리의 다른 글
Effective Typescript - 28 - 유효한 상태만 표현하는 타입을 지향하기 (0) | 2022.01.23 |
---|---|
Effective Typescript - 27 - 함수형 기법과 라이브러리로 타입 흐름 유지하기 (0) | 2022.01.23 |
Effective Typescript - 25 - 비동기 코드에는 콜백 대신 async 함수 사용하기 (0) | 2022.01.23 |
Effective Typescript - 24 - 일관성 있는 별칭(Allias) 사용하기 (0) | 2022.01.23 |
Effective Typescript - 23 - 한꺼번에 객체 생성하기 (0) | 2022.01.22 |