개발언어/TypeScript

타입 단언 (Type Assertions)

Ligion 2021. 4. 12. 15:35

 

타입 단언은 말그대로 컴파일러에게 타입이 이것이다라고 단언하는 것이다.

사용 방법은 두가지이다.

let code: any = 123;
let employeeCode = <number> code;
let employeeCode = code as number;

형변환과는 다르다. 

형변환은 실제로 데이터의 구조를 변환하는 것이고

타입단언은 컴파일러에게 강제하는 것이다.

 

DOM구조에 접근할 때 주로 쓴다.

const button = document.querySelector('.btn')! as HTMLButtonElement;
// button에 HTMLButtonElement구조가 타입단언되면서 지원되는 api를 사용할 수 있다.

 

사용을 잘 못하면 재앙이...

변수 wrong은 array가 아니지만 타입단언을 하면 array의 api를 사용할 수 있다.


Assertions

  • 주장
  • 단언
  • 자기 주장