我有一个 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
。有没有办法实现这个目标?
您可以创建一个类型,只需将
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