let x= 'x'; // string으로 추론
const x = 'x'; // 타입이 'x'
const v = {
x:1,
}
v.x = 3 // 정상
v.x = '3' // error
v.y = 5 // error
const v1 = {
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; }
타입 좁히기는 타입스크립트가 넓은 타입으로부터 좁은 타입으로 진행하는 과정을 말한다.
const el = document.getElementById('foo'); // 타입이 HTMLElement | null
if(el){
el // 타입이 HTMLElement
el.innerHTML = 'Party'.blink();
} else {
el // 타입이 null
alert('No element')_;
}
instanceof, Array.isArray, 태그된 유니온 패턴, 사용자 정의 타입 가드
declare let hasDates : boolean;
const nameTitle = {name:'TEST', title:'TITLE'};
const pharaoh = {
...nameTitle,
...(hasDates ? {start: -123, end: -321} : {})
}
cosnt pharaoh : {
start : number;
end : number;
name : string;
title: string;
} | {
name: string;
title: string;
}
const test = {name:'TEST',location:[1,2]};
const loc = test.location;
loc[0] = 0;
test.location // [0,2]
위의 loc을 별칭이라고 한다. 별칭의 값을 변경하면 원래 속성값에서도 변경된다.
interface Coordinate {
x : number;
y : number;
}
interface BoundingBox {
x : [number,number];
y : [number,number];
}
interface Polygon {
exterior : Coordinate[];
holes : Coordinate[];
bbox?: BoundingBox;
}
function isPointInPolygon(polygon,: Polygon, pt: Coordinate){
const box = polygon.bbox;
if(polygon.bbox){
if(pt.x < box.x[0] || pt.x > box.x[1]) ||
// ~~~ ~~~ box 객체가 undefined일 수 있음
// if문에서 타입을 좁힌 건 bbox / box 객체의 타입을 좁히지 않음
}
};
function isPointInPolygon(polygon,: Polygon, pt: Coordinate){
const { bbox } = polygon.bbox;
if(bbox){
const {x,y} = bbox;
if(pt.x < x[0] || pt.x > x[1]) ||
}
}