Item 24 - 일관성 있는 별칭 사용하기
별칭은 타입스크립트가 타입을 좁히는 것을 방해합니다. 따라서 변수에 별칭을 사용할 때는 일관되게 사용해야 합니다.
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] ||
// ~~~ ~~~ Object is possibly 'undefined'
pt.y < box.y[1] ||
pt.y > box.y[1]
) {
// ~~~ ~~~ Object is possibly 'undefined'
return false
}
}
// ...
}
export default {}
위 코드는 box라는 별칭을 만들었지만 if문에선 사용하지않고 있습니다. 따라서 타입좁히기가 적용이 안되는것이나 마찬가지이기 때문에 box.x 나 box.y 가 undefined 일수도 있다는걸 알려줍니다.
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 (box) {
if (pt.x < box.x[0] || pt.x > box.x[1] || pt.y < box.y[1] || pt.y > box.y[1]) {
// OK
return false
}
}
// ...
}
'별칭은 일괄성 있게 사용한다' 기본원칙을 지키면 위와 같이 오류를 방지할 수 있습니다.
'Typescript' 카테고리의 다른 글
Effective Typescript - 아이템 26 (0) | 2023.05.02 |
---|---|
Effective Typescript - 아이템 25 (0) | 2023.04.23 |
Effective Typescript - 아이템23 (0) | 2023.04.18 |
Effective Typescript - 아이템20~아이템22 (0) | 2023.04.13 |
Effective Typescript - 아이템19 (0) | 2023.04.12 |