What is the difference between type and interface in TypeScript?
What is the difference between type and interface in TypeScript?
In TypeScript, both type
and interface
are used to define the shape of an object or to type a variable. However, they have some differences in their capabilities, syntax, and use cases, which can influence the choice between them depending on the specific requirements of your code.
Syntax and Declaration:
interface
is used to declare a shape for objects and can only represent an object type. It uses the interface
keyword.type
, on the other hand, is more versatile. It can represent not only object types but also primitive types, union types, intersection types, and tuple types. It uses the type
keyword[1][2][3][4][5][6][7].Extensibility:
Implementing and Extending:
extends
keyword, while types use intersection types (&
) for extension[6][7].implements
keyword. While it's also possible for classes to implement types, this is less common and typically involves implementing a type that describes a constructor or function signature[5][6].Compatibility with Advanced Types:
*Performance and Tooling...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào