패스트캠퍼스 데브캠프

김민태의 데브캠프 2기 - type annotation과 type inference

vitamin3000 2024. 11. 8. 14:27

 

우선 정의에 대해 알아보자. 

 

type annotation : 개발자가 타입을 타입스크립트에게 직접 말해주는것

 const rate: nmber = 5;

type inference : 타입스크립트가 알아서 타입을 추론하는 것

 

const rate = 5;

 

타입을 추론하지 못해서 타입 annotation을 꼭 해줘야하는 경우는 아래 3가지 경우이다.

 

 

1. any 타입을 리턴하는 경우

const josn: string = '{"x": 4,  "y" : 7}'
const coordinates = JSON.parse(json)
console.log(coordinates)

 

2. 변수 선언을 먼저하고 나중에 초기화하는 경우

let greeting
reeting = 'hello' // let greeting: any


3. 변수에 대입될 값이 일정치 못하는 경우

 

let num = [-7, -2, 10];
let numAboveZero: boolean | number = false;

for(let i = 0; i< num.lenghth; i==){
	if (num[i] > 0) {
		numAboveZero = num[i]
	}
}