Type Inference (타입 추론)
*// #1*
*// text 변수에 암묵적으로 string 타입으로 (추론되어)할당되어 있다.*
let text = 'hello';
*// #2*
*// message 매개변수 에는 암묵적으로 any 타입으로 (추론되어)할당되어 있다.
// print 함수 에는 암묵적으로 void 타입으로 (추론되어)할당되어 있다.*
function print(message) {
console.log(message);
}
print('hello');
print(1);
*// #3*
*// message 매개변수 에는 암묵적으로 string 타입으로 (추론되어)할당되어 있다.
// dafault parameter 가 string 으로 선언 되어 message에도 string 타입으로 할당되었다.*
function print(message = 'hello') {
console.log(message);
}
print('hello');
print(1); *// Error*
*// #4*
*// add 함수의 return 타입이 number 타입으로 (추론되어)할당되어 있다.*
function add(x: number, y: number) {
return x + y;
}
*// #5*
*// 추론에 추론
// result 변수에는 암묵적으로 number 타입으로 (추론되어)할당되어 있다.*
const result = add(2, 3);
→ 정리하면,
100% 예상되는 타입에는 반드시 타입을 명시할 필요는 없지만,
가독성 향상을 위해 타입을 명시하는 습관을 들이는 것이 좋다.