Câu hỏi phỏng vấn Typescript
Câu hỏi

What is the difference bet...

Câu trả lời

In TypeScript, both unknown and any types allow for the assignment of values of any type, but they differ significantly in how they handle type safety and type checking.

The any Type

The any type is the most permissive type in TypeScript. It allows you to assign any value to a variable declared with this type and perform any operations on such variables without TypeScript's type checking interfering. This means you can access properties, call methods, and pass it around as if it were of any possible type. However, this flexibility comes at the cost of type safety. Using any essentially opts out of TypeScript's type system, making it easy to introduce subtle bugs if you're not careful. It's akin to writing JavaScript without any type checks[1][3][5].

The unknown Type

Introduced in TypeScript 3.0, the unknown type represents a type-safe counterpart to any. Like any, a variable of type unknown can hold any value; however, you cannot perform any operations on unknown values without first performing some form of checking to narrow down its type to a more specific type. This means that while you can assign anything to a variable of type unknown, you must use type assertions or type narrowing (like type guards) before you can use the value in a type-specific way. This adds a layer of safety that helps prevent runtime errors[1][2][3][4][5].

Key Differences

  • Type Safety: unknown is much safer than any because it forces developers to perform type checking before operating on the data, thus catching potential bugs during compile time. In contrast, `any...
senior

senior

Gợi ý câu hỏi phỏng vấn

expert

What is the need of --incremental flag in TypeScript?

middle

How can you allow classes defined in a module to be accessible outside of the module?

senior

How to exclude property from type in TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào