Item19 - 추론 가능한 타입을 사용해 장황한 코드 방지하기
타입스크립트에 익숙하지 않은 개발자는 모든 변수에 타입을 명시해야 한다고 생각합니다. 그러나 타입스크립트는 많은 타입 구문을 필요로 하지 않습니다.
let x:number =12;
let x =12; // 이렇게만 해도 충분
타입스크립트가 굳이 number를 명시하지 않았음에도 불구하고 자연스럽게 추론되어 있음을 확인할 수 있습니다.
이렇게 타입 추론이 된다면 명시적 타입 구문을 필요하지 않습니다. 오히려 코드 가독성을 해칠뿐입니다.
타입스크립트는 더욱 복잡한 객체도 추론 가능합니다.
const person: {
name: string
born: {
where: string
when: string
}
died: {
where: string
when: string
}
} = {
name: 'Sojourner Truth',
born: {
where: 'Swartekill, NY',
when: 'c.1797',
},
died: {
where: 'Battle Creek, MI',
when: 'Nov. 26, 1883',
},
}
------------------------------------
const person = {
name: 'Sojourner Truth',
born: {
where: 'Swartekill, NY',
when: 'c.1797',
},
died: {
where: 'Battle Creek, MI',
when: 'Nov. 26, 1883',
},
}
// 타입을 생략하고 다음과 같이 작성해도 둘다 타입이 동일합니다.
값에 추가로 타입을 작성하는것은 불필요합니다.
배열도 객체와 마찬가지입니다. 타입스크립트는 입력받아 연산을 하는 함수가 어떤 타입을 반환하는지 정확히 알 수 있습니다.
function square(nums:number[]){
return nums.map(x =>x * x);
}
const square = square([1,2,3,4]); // 타입은 number[]
타입이 추론되면 리팩토링 이 쉬워집니다.
interface Product {
id: number
name: string
price: number
}
function logProduct(product: Product) {
const id: number = product.id
const name: string = product.name
const price: number = product.price
console.log(id, name, price)
}
id에 number 가 아닌 string도 들어 있음을 나중에 알게 되었다고 가정하겠습니다.
interface Product {
id: string
name: string
price: number
}
function logProduct(product: Product) {
const id: number = product.id
// ~~ Type 'string' is not assignable to type 'number'
const name: string = product.name
const price: number = product.price
console.log(id, name, price)
}
함수내에서 명시적으로 타입을 선언했기때문에 오류가 발생합니다.
오류를 해결하기위해 함수내에서 타입선언을 하지않고 구현해보겠습니다.
interface Product {
id: string
name: string
price: number
}
function logProduct(product: Product) {
const { id, name, price } = product
//비구조화 할당
console.log(id, name, price)
}
비구조화 할당문을 사용하여 지역변수의 타입이 추론되도록 합니다. 함수내에서 생성된 지역변수는 타입구문을 생략하고 함수 본연의 로직에 집중하는것이 좋습니다.
타입이 추론될 수 있음에도 타입을 명시하고 싶은 상황들이 있습니다. 그중 하나는 객체 리터럴을 정의할 때입니다.
const elmo:Product={
name:"Tickle Me Elmo",
id:"048188 627152",
price:28.99
}
객체리터럴을 정의할때 타입을 명시해주면 잉여 속성 체크가 독장합니다. 변수가 사용되는 순간이 아닌 할당하는 시점에 오류를 잡아줍니다.
만약 타입구문을 제거한다면 잉여 속성 체크가 동작하지않고, 객체를 선언한곳이 아니라 객체가 사용되는 곳에서 오류가 발생합니다.
const furby = {
name:"Furby",
id:630509436963,
price:35
}
logProduct(furby)
// ~~'number'형식은'string'형식에 할당할 수 없습니다.
--------------------
const furby:Product = {
name:"Furby",
id:630509436963,
// id는 string 타입이어야하기때문에 오류발생
price:35
}
요약
- 타입스크립트가 추론할 수 있다면 타입 구문을 작성하지 않는게 좋다.
- 추론될 수 있는 경우에도 객체 리터럴과 함수 반환값은 타입 명시를 고려해야한다. 내부 구현 오류를 쉽게 인지하기위해.
'Typescript' 카테고리의 다른 글
Effective Typescript - 아이템23 (0) | 2023.04.18 |
---|---|
Effective Typescript - 아이템20~아이템22 (0) | 2023.04.13 |
Effective Typescript - 아이템18 (0) | 2023.04.12 |
Effective Typescript - 아이템17 (0) | 2023.04.12 |
Effective Typescript - 아이템16 (0) | 2023.04.11 |