2024.10.27
// 함수 반환에 타입 명시 안 한 경우
const cache: { [ticker: string]: number } = {};
function getQuote(ticker: string) {
if (ticker in cache) {
return cache[ticker];
}
return fetch('https://quotes.example.com/?q=${ticker}')
.then((response) => response.json())
.then((quote) => {
cache[ticker] = quote;
return quote;
});
}
getQuote('MSFT').then(considerBuying);
// 'number | Promise<any>' 형식에 'then1 속성이 없습니다.
// 'number' 형식에 'then' 속성이 없습니다.
// 함수 반환에 타입 명시한 경우
const cache: { [ticker: string]: number } = {};
function getQuote(ticker: string): Promise<number> {
if (ticker in cache) {
return cache[ticker];
// 'number' 형식은 ,Promise<number>, 형식에 // 할당할 수 없습니다.
}
// ...
}widening) : 상수를 사용해서 변수를 초기화할 때 타입을 명시하지 않으면 타입 체커가 결정하는 타입. 타입 체커는 지정된 단일 값을 가지고 할당 가능한 값들의 집합을 유추합니다.const, 타입구문(명시적으로 타입 구문 제공), 문맥(함수의 매개변수로 값을 전달하여 문맥 추가), as const에 익숙해져야 합니다.const vl = { x: 1, y: 2 }; // 타입은 { x: number; y: number; }
const v2 = {
x: 1 as const,
y: 2,
}; // 타입은 { x:1; y:number; }
const v3 = { x: 1, y: 2 } as const; // 타입은 { readonly x: 1; readonly y: 2; }타입 좁히기는 타입스크립트가 넓은 타입으로부터 좁은 타입으로 진행하는 과정을 말합니다.
null 체크const el = document.getElementByld('foo'); // 타입이 HTMLElement | null
if (el) {
el; // 타입이 HTMLElement
el.innerHTML = 'Party Time'.blink();
} else {
el; // 타입이 null
alert('No element #foo');
}instanceof , 속성 체크, Array.isArray 와 같은 일부 내장 함수로도 타입 좁히기가 가능합니다.
태그된 유니온(tagged union), 사용자 정의 타입 가드와 같은 기법으로도 타입을 좁힐 수 있습니다.
분기문 외에도 여러 종류의 제어 흐름을 살펴보며 타입스크립트가 타입을 좁히는 과정을 이해해야 합니다.
({...a, ...b})를 사용하면 됩니다.function isPointlnPolygon(polygon: Polygon, pt: Coordinate) {
const box = polygon.bbox;
if (polygon.bbox) {
if (pt.x < box.x[0] || pt.x > box.x[l] || pt.y < box.y[0] || pt.y > box.y[l]) {
// box 객체가 'undefined*일 수 있습니다.
return false;
}
}
// ...
}function isPointlnPolygon(polygon: Polygon, pt: Coordinate) {
const { bbox } = polygon;
if (bbox) {
const { x, y } = bbox;
if (pt.x < x[0] || pt.x > x[1] || pt.y < y[0] || pt.y > y[1]) {
return false;
}
}
// ...
}as const)을 사용해야 합니다. 그러나 상수 단언을 사용하면 정의한 곳이 아니라 사용한 곳에서 오류가 발생하므로 주의해야 합니다.