개발자가 변수를 선언할 때 타입을 쓰지 않아도 컴파일이 스스로 판단해서 타입을 넣어주는 것
즉, 타입을 생략하고 변수를 선언할 때 대입된 값의 형태를 보고 타입을 추론해서 자동으로 넣게되는 원리이다.let num = 12; num = 'Hello World'; //Error이때 타입 추론은, 리턴 타입에도 잘 쓰일 수 있는데, number 타입 두개가 연산을 한 결과값이 리턴값인 경우, 굳이 함수 타입을 지정하지 않아도 컴파일러가 추론해 판단할 수 있다.
즉, 타입을 생략하고 변수를 선언하거나 초기화할 때 타입이 추론된다.
타입스크립트의 생산성을 높이기 위한 방법이다. 누가봐도 특정 타입인 부분까지 개발자에게 맡기지 않겠다는 뜻이다,
타입이 확실하다고 개발자가 판단되면 컴파일러에게 알려주는 것이다.
즉, 컴파일러가 추론하지 않도록 직접 지시하는 것이다.
하지만, 이는 런타임에는 영향을 미치지 않고 오직 컴파일 과정에서만 사용된다.
컴파일러를 속이는 것과 같으므로, 빨간줄은 뜨지 않지만 오류는 발생할 수 있다.
<> 사용let here: unkown = '타입';
let here_count:number = (<string>here).length;
let here: unkown = '타입';
let here_count:number = (here as string).length;
에러를 줄일 수 있는 방어 코드 기법이다. if문으로 분기를 해서 오류를 줄이는 것도 타입 가드에 해당한다.
function numOrStr(a:number | string){
if(typeof a === 'string') {
a.split(',');
}
if (typeof a === 'number'){
a.toFixed(1);
}
}
class Food {
fruits() {}
}
function favoriteFood(parm: Food | string){
if (parm instanceof Food) {
parm.fruits();
} else {
console.log(parm);
}
}
type Fruits = {type:'fruit', apple: boolean, cost: 'H' | 'L' };
type Salad = {type:'salad', tender: boolean, cost: 'H' | 'L' };
type Yogurt = {type:'yogurt', greak: boolean, cost: 'H' | 'L' };
function isFavorite(a: Fruits | Salad | Yogurt ){
if(a.type === 'fruit'){
a.apple = true;
} else if ( a.type === 'salad') {
a.tender = true
} else {
a.greak = true;
}
}
type 속성이 없을 때는 타입이 같고 속성명이 다른 것을 찾는다.
type Fruits = {apple: boolean, cost: 'H' | 'L' };
type Salad = { tender: boolean, cost: 'H' | 'L' };
type Yogurt = { greak: boolean, cost: 'H' | 'L' };
function isFavorite(a: Fruits | Salad | Yogurt ){
if( 'apple' in a ){
a.apple = true;
} else if ('tender' in a ) {
a.tender = true
} else {
a.greak = true;
}
}
function isNull(data: number[] | null){
if(data && typeof data === 'object')}
for (const number of data){
console.log(number);
}
}
}
이번주 꽤 정신없어서 예시를 하나하나 해보지 못했는데 아티클 보며 코드까지 복습 제대로 했어용,,✨