TypeScript -3-

mh·2022년 5월 2일
0

TypeScript

목록 보기
3/17
post-thumbnail

Photo by Ishan @seefromthesky on Unsplash

Unknown

case)

  • API의 응답을 받았는데 응답값의 Type을 모를때
    -> Unknown
let a:unknown;
  • 이렇게 선언하면 어떤 작업을 할때 이 변수의 타입부터 확인해야 함
let a:unknown;

let b = a + 1

  • type 이 unknown 이므로 허용해주지 않음
  • 먼저 type을 체크해주는 코드를 작성해야 함
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();
}
  • a의 타입이 string임을 확인, toUpperCase함수 사용가능

void

  • 아무것도 return하지 않는 함수를 대상으로 사용
function hello(){
    console.log('x');
}

  • void를 따로 지정 안해줘도 됨, TS가 함수가 return하지 않는다는 걸 자동으로 인식
function hello():void {
    console.log('x');
}
  • 이렇게 써도 되지만 꼭 써야하는건 아님

  • 아래의 코드는 허용되지 않음

function hello(){
    console.log('x');
}

const a = hello()
a.toUpperCase();

  • void타입엔 toUpperCase가 없다 , void는 비어있음

never

  • 함수가 절대 return하지 않을때 사용
  • ex) 함수에서 exception(예외)가 발생할때
function hello():never {
	return "X"
}

function hello():never {
    throw new Error("xxx")
}
  • 오류를 발생시키는 함수를 사용할때 사용
  • never의 타입이 두가지 일 수도 있는 상황
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
    }
}
  • 파라미터를 지정할때는 |(or) &(and)를 사용
  • 각 블록에서 name값
typeof name ==="string"typeof name ==="number"never
  • 만약 코드가 정상적으로 작동했다면(타입이 올바르게 들어왔다면) else 블록은 절대 작동하지 않는다.

정리

배운것

  • void : 가장 많이 쓰게 될거임
  • unknown : 그 다음으로 쓰게 됨
  • never : 거의 안씀
profile
🤪🤪🤪🤪🤪

0개의 댓글