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

What is the difference between type and interface in TypeScript?

Câu trả lời

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.

Key Differences

  1. 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].
  2. Extensibility:

    • Interfaces are open-ended, meaning you can extend them by declaring the same interface name more than once, and TypeScript will merge them into a single interface. This feature is particularly useful for augmenting existing types or interfaces from third-party libraries[7].
    • Type aliases are closed, meaning once you've defined them, you cannot modify or extend them further[7].
  3. Implementing and Extending:

    • Both interfaces and types can be extended, but the syntax differs. Interfaces use the extends keyword, while types use intersection types (&) for extension[6][7].
    • Classes can implement interfaces using the 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].
  4. Compatibility with Advanced Types:

    • Type aliases have the advantage when it comes to defining union types, intersection types, and tuple types. Interfaces cannot directly represent these constructs, although they can reference type aliases that do[2][4][6].
    • Type aliases can also be used for defining mapped types and conditional types, which are not possible with interfaces[4].
  5. *Performance and Tooling...

middle

middle

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

entry

Explain generics in TypeScript

middle

What is Typings in Typescript?

middle

What are different components of TypeScript?

Bình luận

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

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