상추의 IT저장소
TS) 타입 단언(Type Asssertion) 본문
타입 단언(Type Assertion) 이란?
- 타입스크립트가 추론하지 못하는 타입을 as 키워드를 통해 명시해주는 것
- as 뒤에 명시하고자 하는 데이터 타입을 작성 해주면 된다.
- 실제 데이터 타입을 변경하지 않고 타입 에러가 나지 않게끔 한다.
Type Casting과 Type Assertion의 차이점
- Type casting : 데이터의 타입을 변환 -> 실제 타입이 변한다.
- Type assertion : 데이터의 타입을 명시 -> 데이터 타입에 영향을 주지 않는다.
Type Assertion 사용법
// as 를 활용한 type assert
let str : unknown = "String";
let strLength : number = (str as string).length;
// <>를 활용한 type assertion
let something : unknown = "this is string!"
let strLength2: number = (<string>something).length
- unknown 타입을 Type Assertion을 통해서 타입추론을 가능하게 한다.
'Javascript > TypeScript' 카테고리의 다른 글
| TS) 추상 클래스 (Abstract class) (0) | 2023.01.27 |
|---|---|
| TS) generic (0) | 2023.01.23 |
| TS) 타입 지정 (0) | 2023.01.23 |
| TS)Class (0) | 2023.01.17 |
| TS) TS설치 & tsconfig.json 만들기 (0) | 2023.01.17 |