Photo by Ishan @seefromthesky on Unsplash
case)
let a:unknown;
let a:unknown;
let b = a + 1
let a:unknown;
if(typeof a === 'number') {
let b = a + 1
}
이 블록 안에서는 a의 type이 number임이 확인됐기때문에 연산가능
a를 string
으로 활용해보기
let a:unknown;
a.toUpperCase();
if(typeof a === 'string') {
a.toUpperCase();
}
string
임을 확인, toUpperCase함수 사용가능function hello(){
console.log('x');
}
function hello():void {
console.log('x');
}
이렇게 써도 되지만 꼭 써야하는건 아님
아래의 코드는 허용되지 않음
function hello(){
console.log('x');
}
const a = hello()
a.toUpperCase();
function hello():never {
return "X"
}
function hello():never {
throw new Error("xxx")
}
function hello(name:string|number):never {
name + 1
}
name은 문자열일수도 숫자일수도 있기 떄문에 아래와 같은 에러 발생
typeof를 이용해서 다음과 같이 작성
function hello(name:string|number){
if(typeof name === "string") {
name
} else if (typeof name === "number") {
name
} else {
name
}
}
typeof name ==="string" | typeof name ==="number" | never |
---|---|---|
![]() | ![]() | ![]() |
else
블록은 절대 작동하지 않는다.배운것