When to use never and unknown in TypeScript
Blog post from LogRocket
TypeScript, a language designed with principles of type theory, offers practical features such as the never and unknown types, which are foundational yet complementary aspects of its type system. The never type represents an empty set, indicating that no value can be assigned to it, making it a subtype of every other type and an identity in union operations. In contrast, the unknown type is the top type, encompassing all possible values and serving as a supertype for every other type, which requires type narrowing for safe operations. Type inference and type annotations in TypeScript help ensure variables adhere to specified data types, promoting robust error-checking. Type assertions and type guards provide mechanisms to refine or confirm types within code, enhancing safety and clarity. The article further explores conditional types, using examples to illustrate how TypeScript's system effectively narrows types and manages type safety, advocating for the judicious use of never, unknown, and avoiding any unless necessary.