
어떤 변수가 타입이 아직 불확실할때 Narrowing을 해줘야 에러가 안난다.
<script>
function 에러함수(x :number|string){
return x +1
}
</script>
type이 하나로 확정되지않아 에러가 발생하게 된다.
이럴 경우 if문을 써서 함수를 고쳐보자
<script>
function 네로잉함수(x :number|string){
if(typeof x === 'number'){
return x +1
}
</script>
컴파일러에게 표명하는 것이다. 이 문법은 타입이 100% 확실할때 써야한다. 왜냐면 타입을 덮어씌워버려서 버그를 못잡아주기 때문이다.
❗ 타입을 a에서 b로 변경하는게 아님
arr[0]= x as number => 왼쪽에있는 것(x)을 number로 덮어씌워라는 것
생성자의 prototype 속성이 객체의 프로토타입 체인 어딘가 존재하는지 판별한다.
<script>
// 생성자 정의
function C(){}
function D(){}
var o = new C();
// true, 왜냐하면 Object.getPrototypeOf(o) === C.prototype
o instanceof C;
// false, 왜냐하면 D.prototype이 o 객체의 프로토타입 체인에 없음
o instanceof D;
o instanceof Object; // true, 왜냐하면
C.prototype instanceof Object // true
</script>
문제설명
문자와 숫자가 섞인 array를 입력하면 깔끔하게 숫자로 변환되어 리턴해주는 함수를 만들어라.
solution
<script>
function home0114(x :(number|string)[]){
let arr :number[]=[];
x.forEach((o)=>{
if(typeof o ==='string'){
arr.push(parseInt(o))
}else{
arr.push(o)
}
})
return arr
}
console.log("정답",home0114([123,'3']))
</script>
console확인

🔍 해결과정
1. 숫자타입의 배열 변수를 생성한다. arr
2. forEach 반복문으로 파라미터 배열 인자에 if문을 돌려줌
3. if문 조건은 string타입의 인자를 정수로변환시켜 arr에 푸쉬하기
4. string타입이 아니라면 number타입이므로 그대로 arr에 푸쉬하기