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

How to add types to an interface from another interface or extend types in TypeScript?

Câu trả lời

In TypeScript, interfaces are a powerful way to define contracts within your code and ensure that the objects adhere to a specific structure. When it comes to adding types from one interface to another or extending types, TypeScript provides several mechanisms to achieve this, primarily through interface inheritance and type intersection.

Interface Inheritance

Interface inheritance allows one interface to extend another, effectively inheriting its properties and methods. This is done using the extends keyword. When an interface extends another, it incorporates the properties of the parent interface in addition to its own properties. This mechanism is useful for creating a hierarchy of interfaces that build upon each other, adding more specific properties or methods as the hierarchy progresses.

typescript Copy
interface Mailable {
  send(email: string): boolean;
  queue(email: string): boolean;
}

interface FutureMailable extends Mailable {
  later(email: string, after: number): boolean;
}

In the example above, FutureMailable extends Mailable, meaning it has the send and queue methods from Mailable, plus its own later method[17].

Type Intersection

TypeScript also allows the combination of types through intersection types. While not directly related to interfaces, intersection types can be used to combine multiple types, including interfaces, into a new type that includes all properties of the combined types. This is achieved using the & operator.

typescript Copy
interface Event {
  name: string;
  dateCreated: string;
}

interface UserEvent {
  UserId: string;
}

type ExtendedEvent = Event & UserEvent;

In this example, ExtendedEvent is a type that includes all properties from both Event and UserEvent[1].

Using Generics with Interfaces

Another way to add or extend types in interfaces is through the use of generics. Generics provide a way to create reusable components by creating a placeholder for a type that is specified when the component is used.

typescript Copy
interface Repository<T> {
  findById(id: string): ...
middle

middle

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

expert

How the never datatype can be useful?

entry

Do we need to compile TypeScript files and why?

senior

Why is the infer keyword needed in TypeScript?

Bình luận

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

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