从泛型的键推断 dto 类成员

问题描述 投票:0回答:1

我有一个 QueryParams 的 dto 类,我通过以下方式声明它:

class QueryParams<T> {
  search?: string;

  page?: number;

  ...
}

我必须在 QueryParams 类中做什么来告诉打字稿,我希望它成为 T 的键,而不是显式声明 search

例如,如果我有

class AnotherEntity {
  prop_1: string
  prop_2: number
  prop_3: string
}

const query: QueryParamsDto<AnotherEntity>

我希望能够做到

query.prop_1
query.prop_2
query.prop_3
query.page
。有没有办法实现这个目标?

typescript entity typeorm typescript-generics dto
1个回答
0
投票

您可以创建一个类型,只需将

T
的所有成员设为可选,并将其与您需要的任何其他属性相交。

type QueryParams<T> = Partial<T> & { page?: number }

并像这样使用它:

type AnotherEntity = {
  prop_1: string
  prop_2: number
  prop_3: string
}

declare const query: QueryParams<AnotherEntity>
query.prop_1 = 'abc' // fine
query.prop_2 = 123 // fine
query.prop_3 = 'def' // fine
query.prop_47 = 'prop_47' // type error

看游乐场

© www.soinside.com 2019 - 2024. All rights reserved.