
let text = "hello"; // let text: string // text = 1; // Type 'number' is not assignable to type 'string'
위처럼 text 변수 명에 hello를 할당하였더니 변수 타입이 string으로 추론되어 자동으로 결정되었다.
이후 타입이 number값인 1을 재할당하니 에러가 발생한다. (기존의 text 타입이 string으로 결정되었기 때문이다.)
const print = (message = "안녕하세요") => { // (parameter) message: string console.log(message); }; print(); // 안녕하세요 print("반갑습니다."); // 반갑습니다. print(1); // Argument of type '1' is not assignable to parameter of type 'string | undefined' // const add = (x = 1, y = 2) => { return x + y; }; const result = add(); // const result: number console.log(result); //
특정 함수의 인자의 타입값을 따로 지정하지 않고, default 값에 따라 타입이 추론되어 지정될 수 있다.
add 함수의 경우, 인자들이 숫자값이므로 number로 타입이 추론되어 결정되었다. 또한 result값도 add의 return값이 number 타입을 갖고 있으므로 위같은 결과를 확인할 수 있었다.
드림코딩 엘리님의 TS 및 OPP 강의