TypeScript는 JavaScript로 컴파일된다.
⇒ 브라우저가 이해하는 언어는 JavaScript이기 때문!
TypeScript가 제공하는 보호장치는 TypeScript가 JavaScript로 변환되기 전에 발생한다.
⇒ 유저가 코드를 실행하는 런타임에 발생하는 것이 아닌 컴파일 시 발생!
이로 인해 TypeScript 코드에 에러가 있으면 그 코드는 JavaScript로 컴파일되지 않는다.
const nico = {
nickname: "nick"
}
nico.hello()
// Err: property 'hello' does not exist on type '{ name: string }'.
[1, 2, 3, 4] + false
// Err: operator '+' cannnot be applied to types 'number[]' and 'boolean'
function divide(a, b) {
return a / b
}
divide("hello")
// Err: Expected 2 arguments, but got 1.
모두 작성하자마자 바로 에러가 표시된다.
⇒ 컴파일 시 에러 표시❗️
let b : boolean = "x" // Err: Type 'string' is not assignable to type 'boolean'
위처럼 타입을 명시하는 것이 TypeScript의 문법이며, Type Checker와 소통하는 방식이다.
let a = "hello" // let a: string
a = "bye"
a = 1 // Err: Type 'number' is not assignable to type 'string'
a
가 string 타입이라는 걸 추론해 준다.
string을 string으로 바꾸는 건 가능하지만, string을 number로 바꾸는 건 ❌
let b : boolean = false
let b = false
두 번째 경우 Type Checker에게 타입을 추론하는 것을 허용하고 있다.
✨ 이처럼 TypeScript가 타입을 추론하도록 하는 것이 더 쉽고 코드도 짧아 가독성이 좋다!
let c = [1, 2, 3] // let c: number[]
c.push("1") // Err: Argument of type 'string' is not assignable to type 'number'
마찬가지로, string을 number 배열에 넣을 수 없다.
let c = [] // let c: any[]
let c : number[] = []
c.push("1") // Err: Argument of type 'string' is not assignable to type 'number'
위처럼 빈 배열인 경우, TypeScript가 타입을 추론할 수 없으므로 타입을 명시해주는 것이 좋다.
✨ 그러나 위에서 언급하였듯, 명시적 표현은 최소한으로 사용하고, TypeScript가 타입을 추론하도록 두는 것이 가장 좋다!
const player = {
name: "nico"
}
/*
const player: {
name: string;
}
*/
player.hello // Err: property 'hello' does not exist on type '{ name: string }'.
위 에러는 TypeScript의 추론이 동작하였기 때문에 발생하는 에러이다.