我正在尝试为查询对象创建TypeScript接口。
interface Comparison {
op: '=' | '>' | '<';
field: string;
value: any;
}
interface Conjunction {
op: 'and' | 'or';
queries: Array<Comparison>;
}
type Query = Comparison | Conjunction;
所以查询可以很简单(比较(,比如
{
"op": "=",
"field": "score",
"value": 5
}
或更复杂的(连词(,如
{
"op": "and",
"queries": [
{
"op": ">",
"field": "score",
"value": 1
},
{
"op": "<",
"field": "score",
"value": 10
}
]
}
我最终将一些输入过滤器对象映射到我的查询对象中。
// One possible input for a simple comparison filter
// const inputFilter = {
// field: 'someField',
// type: 'eq',
// value: 'someValue'
// };
// An input for a more complex filter
const inputFilter = {
field: 'someField',
type: 'range',
value: 5,
valueEnd: 10
};
const query: Partial<Query> = {
field: inputFilter.field
};
switch (inputFilter.type) {
case 'eq':
query.op = '=';
query.value = inputFilter.value;
break;
case 'range':
query.op = 'and'; // ERROR: Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'
query.queries = [
{ field: inputFilter.field, op: '>', value: inputFilter.value },
{ field: inputFilter.field, op: '<', value: inputFilter.valueEnd }
]; // ERROR: Property 'queries' does not exist on type 'Partial<Comparison>'
break;
// ...other cases / default...
}
我得到两个错误。首先是当我尝试将query.op
设置为'and'
Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'
第二个是当我键入以设置query.queries
Property 'queries' does not exist on type 'Partial<Comparison>'
这是一个TypeScript Playground,可以看到它的实际效果。
我是不是误解了Partial<Query>
在做什么?我希望这意味着我可以有一个部分比较或部分结合对象。
作为记录,使用Partial<Comparison> | Partial<Conjunction>
也不起作用。
Conjunction
对象没有field
属性
interface Conjunction {
op: 'and' | 'or';
queries: Comparison[];
}
const query: Partial<Query> = {
field: inputFilter.field
};
这意味着您的查询将始终属于Comparison
类型。