TypeScript | Type Assertion

권기현·2021년 2월 10일
2

TypeScript

목록 보기
3/3

Assertion: 컴퓨터 프로그래밍에서 표명(表明), 가정 설정문(假定設定文) 또는 어서션(영어: assertion)은 프로그램 안에 추가하는 참·거짓을 미리 가정하는 문이다. 개발자는 해당 문이 그 문의 장소에서 언제나 참이라고 간주한다. 런타임 중에 표명이 거짓으로 평가되면 표명 실패(assertion failure)를 초래하며 이 상황에서는 일반적으로 실행이 중단된다.

TypeScript에서는 참, 거짓이 외의 다른 타입에 대해서도 "미리 가정" 한다.

💩 결론부터 말하자면 Type Assertion을 쓰는 것은 좋은 것은 아니다!
그렇다면 언제 쓰는 것이고 쓰면 안될까?

Type Assertion

at. TypeScript handbook
Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does.Usually, this will happen when you know the type of some entity could be more specific than its current type.
Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but it performs no special checking or restructuring of data. It has no runtime impact and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

🌟 When can we use ?

타입이 없는 JS파일과 함께 써야하는 경우에 불가피하게 써야하는 경우가 있다.

JS는 타입이 없기에 TypeScript는 Compile단계에서 확인하지 못한다. 이때 사용자(개발자)가 JS의 변수나 리턴값에 대한 타입을 확신한다고 TypeScript를 안심(?)시킬때 Type Assertion을 사용한다.

🌟❗️개발자가 코드를 작성하는 시점에서, 타입에 대해서 정말 100% 확신할 수 있을 때 사용하자

🚫 What is the problem with ?

그래서 코드를 작성하는 시점에서는 TypeScript가 모르는 상황이므로 에러나 경고메세지가 뜨지는 않고 → Runtime때 Type check error가 생겨 undefined가 리턴되거나 💩어플리케이션이 죽을 수 있다.

ex)

// in JS
const someValue = 1;

// in TS
// 개발자는 someValue가 Arrat<number>라고 확신! -> Type Assertion!!
// Type Assertion을 했기 때문에 push() 를 사용가능하다.
console.log( (someValue as Array<number>).push( 2 ));

// at. Compile Time -> 문제 없음!

// at. Runtime -> 💥💥💥
// TypeError: someValue.push is not a function 💩💩💩
// Application Die!!😭

Two forms (for casting)

1) as-syntax:

let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

2) “angle-bracket” syntax:

let someValue: unknown = "this is a string";
let strLength: number = (<string>someValue).length;

=> 두가지 모두 같고 선호도에 따라서 쓰면 된다. 그러나! TypeScript를 React의 JSX문법과 함께 쓸 때는 "as-syntax"를 쓰는 것이 권장된다.

! => " 나는 절대 절대 장담 할 수 있어!! "

// at JS
// JS에서는 number[]를 반환한다고 개발자가 확신한 함수가 있다.
// 사실은 number[]를 반환하거나 undefined 를 반환하는 함수이다.
// TS에서는 다음과 같이 표현되는 함수
  function returnNumbersArr(): number[] | undefined {
    return undefined;
  }

// at TS
// 개발자는 numbers는 number[]라고 확신을 했기 때문에 "!" 를 붙여 Type Assertion

//case1 : 함수를 실행하는 곳에서 !를 붙여서 Type Assertion
const numbersArr = findNumbers()!;
numbersArr.push(2); // 

// case2 : 할당된 변수 뒤에 !
const const numbersArr = findNumbers();
numbersArr!.push(2); // 

위와 같이 TypeScript는 numberArr의 타입이 number[] | undefined 로 알다가 "!"를 작성해줌으로서 number로 타입을 정한다.

참고자료 | TS Handbook - Type Assertion

profile
함께 일하고 싶은 개발자를 목표로 매일을 노력하고, 옷을 좋아하는 권기현 입니다.

0개의 댓글