首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何基于另一种类型在TypeScript中定义类型,使某些属性成为可选属性,并删除其他属性?

如何基于另一种类型在TypeScript中定义类型,使某些属性成为可选属性,并删除其他属性?
EN

Stack Overflow用户
提问于 2022-10-31 00:17:13
回答 1查看 21关注 0票数 0

假设我有一个DTO (数据传输对象)表示模型。此DTO包括模型ID、创建日期和最后更新日期。

我想在此基础上定义另一种类型,其中我只想在定义了模型DTO的所有属性时,但是使ID是可选的,这样新的DTO可以作为一个通用的DTO来创建新的实例和更新现有的实例( CreateUpdateSomeModelDTO类型)?

或者,我希望从这种新类型中删除创建日期和最后更新日期,如果这些日期应该由服务器或数据库设置,而不是由客户端设置。

如何根据这个初始的DTO类型在TypeScript中定义这个新类型:

代码语言:javascript
复制
type Product = {
    id: string;
    name: string;
    shortDescription: string | null;
    imageUrl: string | null;
    createdAt: Date;
    updatedAt: Date;
    productCategoryId: string;
}
EN

回答 1

Stack Overflow用户

发布于 2022-10-31 00:17:13

我们可以使用标准库类型实用程序OmitPartialPick来实现这一点。

在TypeScript 4.7中,这些实用程序类型定义为:

代码语言:javascript
复制
/** Construct a type with the properties of T except for those in type K. */
type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }

/** Make all properties in T optional */
type Partial<T> = { [P in keyof T]?: T[P] | undefined; }

/** From T, pick a set of properties whose keys are in the union K */
type Pick<T, K extends keyof T> = { [P in K]: T[P]; }

鉴于模型类型:

代码语言:javascript
复制
type Product = {
    id: string;
    name: string;
    shortDescription: string | null;
    imageUrl: string | null;
    createdAt: Date;
    updatedAt: Date;
    productCategoryId: string;
}

解决办法是:

代码语言:javascript
复制
type CreateUpdateProductInput = Omit<
  Product,
  "id" | "createdAt" | "updatedAt"
> &
  Partial<Pick<Product, "id">>;

Omit从输入类型中移除在联合中定义的属性,并保留rest,Pick只选择id属性,Partial使该属性成为可选属性。&用于交叉结果类型,创建一个新类型,该类型具有所有相交类型的所有属性。

这不是问题所在,但值得一提的是,您还可以通过与另一个类型定义相交来向该定义添加其他属性,例如:

代码语言:javascript
复制
type CreateUpdateProductInput = Omit<
  Product,
  "id" | "createdAt" | "updatedAt"
> &
  Partial<Pick<Product, "id">> & { extraCustomField: string };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74257654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档