Junior — Middle
In what cases is it recommended to use types with the 'type' keyword in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, the keyword type is used to declare custom types, especially when defining aliases for complex or union types, as well as for describing primitive, union, or intersection types.
It is recommended to use type in the following cases:
- To create aliases for primitive types or unions:
type ID = string | number; - To describe complex types that do not require declaring an interface, such as unions or intersections:
type Response = Success | Error; - When you need to define types for functions, tuples, or other structures not directly supported by interfaces.
Unlike interface, type is more flexible in expressing complex types but does not support declarative extension (extends) or declaration merging.