TypeScript - unknown
Unknown
- 응용프로그램을 작성할 때 모르는 변수의 타입을 묘사해야 할 수도 있다.
- 이러한 값은 동적 콘텐츠(예: 사용자로부터, 또는 우리 API의 모든 값을 의도적으로 수락하기를 원할 수 있다.)
- 컴파일러와 미래의 코드를 읽는 사람에게 이 변수가 무엇이든 될 수 있음을 알려주는 타입을 제공하기를 원하므로 unknown 타입을 제공한다.
declare const maybe: unknown;
const aNumber: number = maybe;
// Type 'unknown' is not assignable to type 'number'.
if (maybe === true) {
const aBoolean: boolean = maybe;
// const aString: string = maybe;
// 간단한 타입가드 형태
// Type 'boolean' is not assignable to type 'string'.
}
if (typeof maybe === 'string') {
maybe; // 타입 오브 타입가드라고 부른다.
// const maybe: string
const aString: string = maybe;
const aBoolean: boolean = maybe;
// Type 'string' is not assignable to type 'boolean'.
}
- TypeScript 3.0 버전부터 지원
- any와 짝으로 any 보다 Type-safe한 타입이다.
- any와 같이 아무거나 할당할 수 있다.
- 컴파일러가 타입을 추론할 수 있게끔 타입의 유형을 좁히거나
- 타입을 확정해주지 않으면 다른 곳에 할당할 수 없고, 사용할 수 없다.
- unknown 타입을 사용하면 runtime error를 줄일 수 있을 것 같다.
- 사용 전에 데이터의 일부 유형의 검사를 수행해야 함을 알리는 API에 활용할 수 있다.
Notion : https://torpid-pasta-de7.notion.site/Basic-Types-7c1eff4fb5f3449e932fb1d157da1f25
'TypeScript > Basic-Types' 카테고리의 다른 글
TypeScript - void (0) | 2022.02.07 |
---|---|
TypeScript - never (0) | 2022.02.07 |
TypeScript - any (0) | 2022.02.07 |
TypeScript - Tuple (0) | 2022.02.07 |
TypeScript - Array (0) | 2022.02.07 |
댓글
이 글 공유하기
다른 글
-
TypeScript - void
TypeScript - void
2022.02.07 -
TypeScript - never
TypeScript - never
2022.02.07 -
TypeScript - any
TypeScript - any
2022.02.07 -
TypeScript - Tuple
TypeScript - Tuple
2022.02.07