假设我有一个DTO (数据传输对象)表示模型。此DTO包括模型ID、创建日期和最后更新日期。
我想在此基础上定义另一种类型,其中我只想在定义了模型DTO的所有属性时,但是使ID是可选的,这样新的DTO可以作为一个通用的DTO来创建新的实例和更新现有的实例( CreateUpdateSomeModelDTO类型)?
或者,我希望从这种新类型中删除创建日期和最后更新日期,如果这些日期应该由服务器或数据库设置,而不是由客户端设置。
如何根据这个初始的DTO类型在TypeScript中定义这个新类型:
type Product = {
    id: string;
    name: string;
    shortDescription: string | null;
    imageUrl: string | null;
    createdAt: Date;
    updatedAt: Date;
    productCategoryId: string;
}发布于 2022-10-31 00:17:13
我们可以使用标准库类型实用程序Omit、Partial和Pick来实现这一点。
在TypeScript 4.7中,这些实用程序类型定义为:
/** 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]; }鉴于模型类型:
type Product = {
    id: string;
    name: string;
    shortDescription: string | null;
    imageUrl: string | null;
    createdAt: Date;
    updatedAt: Date;
    productCategoryId: string;
}解决办法是:
type CreateUpdateProductInput = Omit<
  Product,
  "id" | "createdAt" | "updatedAt"
> &
  Partial<Pick<Product, "id">>;Omit从输入类型中移除在联合中定义的属性,并保留rest,Pick只选择id属性,Partial使该属性成为可选属性。&用于交叉结果类型,创建一个新类型,该类型具有所有相交类型的所有属性。
这不是问题所在,但值得一提的是,您还可以通过与另一个类型定义相交来向该定义添加其他属性,例如:
type CreateUpdateProductInput = Omit<
  Product,
  "id" | "createdAt" | "updatedAt"
> &
  Partial<Pick<Product, "id">> & { extraCustomField: string };https://stackoverflow.com/questions/74257654
复制相似问题