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

Typescript 如何向映射类型添加类型约束?,typescript,mapped-types,Typescript,Mapped Types,我正试图给这本书增加更多的打字 我有一个目标 interface Person { name: string; age: number } 我想创建一个查询对象,只允许操作员在age字段上操作,因为它是一个数字,而不是name字段 {age:{$gt:21}}将有效,但不是{name:{$gt:21} 差不多 type MongoConditions<T> = { [P in keyof T]?: T[P] | { $gt: number }; // This co

我正试图给这本书增加更多的打字

我有一个目标

interface Person { name: string; age: number }
我想创建一个查询对象,只允许操作员在
age
字段上操作,因为它是一个数字,而不是
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
};
类型MongoConditions={
[P在keyof T]?:T[P]|
{$gt:number};//仅当T[P]是一个数字时才允许此条件
};
所以这应该是允许的

const condition: MongoConditions<Person> = {
    age: { $gt: 21 },
    name: 'foo'
}
const条件:MongoConditions={
年龄:{$gt:21},
姓名:“富”
}
但这将导致汇编失败:

const condition3: MongoConditions<Person> = {
    age: 21,
    name: { $gt: 21 }
}
const条件3:MongoConditions={
年龄:21岁,
名称:{$gt:21}
}
您可以使用仅允许在“编号”字段上使用查询运算符:

类型MongoConditions={
[P在keyof T]?:T[P]扩展了数?(T[P]{$gt:number}):T[P];
};

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