如何向映射类型添加类型约束?

How to add a type constraint to a mapped type?

我正在尝试向 MongoDB query system 添加更多类型。

我有对象

interface Person { name: string; age: number }

我想创建一个只允许在 age 字段上使用运算符 $gt 的查询对象,因为它是一个数字,而不是 name 字段。

{ age: { $gt: 21 } } 有效,但 { name: { $gt: 21 } }

无效

类似

type MongoConditions<T> = {
    [P in keyof T]?: T[P] |
    { $gt: number }; // This condition should be allowed only if T[P] is a number
};

所以这应该被允许

const condition: MongoConditions<Person> = {
    age: { $gt: 21 },
    name: 'foo'
}

但这应该会导致编译失败:

const condition3: MongoConditions<Person> = {
    age: 21,
    name: { $gt: 21 }
}

您可以使用 conditional type 仅在 "number" 字段上允许查询运算符:

type MongoConditions<T> = {
    [P in keyof T]?: T[P] extends number ? (T[P] | { $gt: number }) : T[P];
};

Playground