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

How to exclude property ...

Câu trả lời

In TypeScript, excluding properties from types is a common task that can be achieved using various methods, primarily through utility types such as Omit. Below, I'll explain the primary methods to exclude properties from types in TypeScript, focusing on the Omit utility type, along with other relevant techniques.

Using the Omit Utility Type

The Omit utility type is one of the most straightforward and commonly used methods to exclude properties from a type. It creates a new type by omitting the specified keys from an existing type.

Syntax

typescript Copy
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
  • T is the original type from which properties are to be omitted.
  • K is the union type of the keys (property names) to be omitted from T.

Example

Suppose you have a User type and you want to create a new type that excludes the password property:

typescript Copy
interface User {
  id: number;
  name: string;
  password: string;
}

type UserWithoutPassword = Omit<User, 'password'>;

const user: UserWithoutPassword = {
  id: 1,
  name: 'John Doe'
  // password is not included here
};

In this example, UserWithoutPassword is a new type identical to User but without the password property[7][12].

Other Methods to Exclude Properties

Using Mapped Types with Conditional Types

You can also create custom types that exclude properties by combining mapped types with conditional types:

typescript Copy
type ExcludeProperty<T, K extends keyof T> = {
    [P in keyof T as Exclude<P, K>]: T[P]
};

type UserWithoutPassword = ExcludeProperty<User, 'password'>;

This method involves more complex type manipulation but offers flexibility for more advanced scenarios[2].

Manual Exclusion with Intersection Types

Another less common approach involves using intersection types combined with types where the excluded property is set to never:

typescript Copy
type User = {
  id: number;
  name: string;
  password: string;
};

type ExcludePassword = {
 ...
senior

senior

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

expert

Explain the difference between declare enum vs declare const enum

expert

What is one thing you would change about TypeScript?

junior

What is the difference between Classes and Interfaces in Typescript?

Bình luận

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

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