0

在 NestJS 中,我想PickType()与一个具有嵌套类属性的类一起使用。

例子:

export class Product {
    status: string;
    payment: {
      status: string;
      type: string;
   }
}

它应该导致如下 DTO 的招摇文档:

class PartialClass {
    payment: {
       status: string,
       type: string
    }
}

但是以下实现不起作用:

class PartialClass {
    @ApiProperty({
      type: () => PickType(Videochat, ['payment']),
     })
    payment: Pick<Videochat['payment'], 'type' | 'status'>;
}

它返回一个空的支付类属性:

class PartialClass {
    payment: {
    }
}

所以我猜 PickType 不能处理嵌套类型。

我也试过:

type: () => PickType(PickType(Videochat, ['payment']), ['status', 'type'])

但它也不起作用。

4

1 回答 1

-1

你可以这样处理,假设我们有以下类:

type User = {
  id: number,
  name: string,
  address: {
    street: string,
    zipcode: string,
    geo: {
      lat: string,
      lng: string,
    },
  },
};

选择带有地址的用户,你可以简单地做type UserWithOnlyAddress = Pick<User, 'address'>;

如果您必须选择具有地址街道的用户,则只有您可以处理它:

type Pick2<T, K1 extends keyof T, K2 extends keyof T[K1]> = {
  [P1 in K1]: {
    [P2 in K2]: (T[K1])[P2];
  };
};


type UserWithOnlyStreetAddress = Pick2<User, 'address', 'street'>;

并在三个层次上采摘

type UserWithOnlyGeoLat = Pick3<User, 'address', 'geo', 'lat'>;

type User = {
  id: number,
  name: string,
  address: {
    street: string,
    zipcode: string,
    geo: {
      lat: string,
      lng: string,
    },
  },
};

type Pick3<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]> = {
  [P1 in K1]: {
    [P2 in K2]: {
      [P3 in K3]: ((T[K1])[K2])[P3];
    };
  };
};
于 2021-10-26T12:06:03.357 回答