TIL 49 | Type Inference
Type Inference(타입 추론)
Inference
- TS에서 변수 명에 특정 값을 할당할 때, 타입을 따로 명시하지 않았을 경우 알아서 타입이 자동으로 결정되는 것을 말한다.
let text = "hello"; // let text: string
//
text = 1; // Type 'number' is not assignable to type 'string'
-
위처럼 text 변수 명에 hello를 할당하였더니 변수 타입이 string으로 추론되어 자동으로 결정되었다.
-
이후 타입이 number값인 1을 재할당하니 에러가 발생한다. (기존의 text 타입이 string으로 결정되었기 때문이다.)
Intersection in default
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 타입을 갖고 있으므로 위같은 결과를 확인할 수 있었다.
Reference
-
-
-
드림코딩 엘리님의 TS 및 OPP 강의
Author And Source
이 문제에 관하여(TIL 49 | Type Inference), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://velog.io/@dydalsdl1414/TIL-49
저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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 강의
Author And Source
이 문제에 관하여(TIL 49 | Type Inference), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@dydalsdl1414/TIL-49저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)