assertion문법 (타입 덮어쓰기)
function 내함수1 (x :number | string) {
let array :number[] = [];
array[0] = x as number;
}
내함수1(123);
- union type을 하나의 타입으로 narrowing 시킬때 assertion 사용한다.
- 무슨 타입이 들어올지 백퍼 확실할때 쓴다.
- 그래서 굳이 쓸 필요가 없음, 그냥 if문으로 narrowing 하면 된다. as문법쓰면 버그추적 못하니깐.
- 남의코드 수정할때 이거 분명 이 타입인데 왜이러는지 모르겠을 때 디버깅용, 비상용으로 씀..
task1.
function cleaningFn(x :(number|string)[]) {
let cleanedFn : number[] = [];
x.forEach((p) => {
if (typeof p === 'string') {
cleaned.push(parseFloat(p))
} else {
cleande.push(p)
}
})
return cleaned
}
console.log(cleaned([12, '2', 121, '231']))
task2.
let 철수샘 = { subject : 'math' }
let 영히샘 = { subject : ['science', 'english'] }
let 밍수샘 = { subject : ['science', 'art', 'musique'] }
function 담당과목 (x :{subject : string | string[]}) {
if (typeof x.subject === 'string') {
return x.subject
} else if (Array.isArray(x.subject)) {
return x.subject[x.subject.length -1]
} else {
return '없음'
}
}
console.log( 담당과목( {subject : ['english', 'art']} ) )