일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 블로그 서비스 최적화
- 이벤트
- pr review
- js pattern
- 자바스크립트 패턴
- 스코프
- 브라우저의 렌더링 과정
- unique identifiers
- mixin pattern
- 진행기록
- 학습내용정리
- DOM
- 프론트엔드 성능 최적화 가이드
- peerdependencies
- 제너레이터와 async/await
- 이미지 갤러리 최적화
- js pattern
- const
- Babel과 Webpack
- version management
- 프로그래머스
- 새 코드 받아오기
- 딥다이브
- 자바스크립트
- 올림픽 통계 서비스 최적화
- package management
- 커리어
- 모던 자바스크립트 Deep Dive
- middleware pattern
- 자바스크립트 딥다이브
- Today
- Total
Dev Blog
Difference "any VS unknown " 본문
Difference "any VS unknown "
Yongjae Kim 2021. 7. 5. 12:45[..] unknown which is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
let myVar: unknown;
let myVar1: unknown = myVar; // No error
let myVar2: any = myVar; // No error
let myVar3: boolean = myVar; // Type 'unknown' is not assignable to type 'boolean'
let vAny: any = 10; // We can assign anything to any
let vUnknown: unknown = 10; // We can assign anything to unknown just like any
let s1: string = vAny; // Any is assignable to anything
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)
// The following operations on myVar all give the error:
// Object is of type 'unknown'
myVar[0];
myVar();
myVar.length;
new myVar();
vAny.method(); // Ok; anything goes with any
vUnknown.method(); // Not ok; we don't know anything about this variable
For more detail,
any type
The any type represents all possible JS values. Every type is assignable to type any. Therefore the type any is an universal supertype of the type system. The TS compiler will allow any operation on values typed any.
In many occasions this is too lenient of the TS compiler. i.e. it will allow operations which we could have known to be resulting into a runtime error.
unknown type
The unknown type represents (just like any) all possible JS values. Every type is assignable to type unknown. Therefore the type unknown is another universal supertype of the type system (alongside any).
However, the TS compiler won't allow any operation on values typed unknown. Compare to the runtime error
which can be arised on using any type, unknown type prevent this runtime error when compiling.
Furthermore, the unknown type is only assignable to the type any.
Source from
'Development Notes > Javascript & Typescript' 카테고리의 다른 글
const 는 값을 변경할 수 없다? Nope. (0) | 2022.11.25 |
---|---|
Type inference & Type annotation (0) | 2021.09.01 |
The JavaScript + Firestore Tutorial (0) | 2021.05.05 |