My goal is to develop TypeScript interfaces for a query object.
interface Comparison {
op: '=' | '>' | '<';
field: string;
value: any;
}
interface Conjunction {
op: 'and' | 'or';
queries: Array<Comparison>;
}
type Query = Comparison | Conjunction;
The query structure can either be simple (Comparison) like
{
"op": "=",
"field": "score",
"value": 5
}
or more complex (Conjunction) like
{
"op": "and",
"queries": [
{
"op": ">",
"field": "score",
"value": 1
},
{
"op": "<",
"field": "score",
"value": 10
}
]
}
I am mapping an input filter object into my query object.
// 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...
}
Two errors occur. The first one when I set query.op
to 'and'
Type '"and"' is not assignable to type '"=" | ">" | "<" | undefined'
The second one when trying to set query.queries
Property 'queries' does not exist on type 'Partial<Comparison>'
You can see the code in action on the TypeScript Playground.
Is my understanding of Partial<Query>
incorrect? I believed it indicated having a partial comparison or conjunction object.
Just to note, using
Partial<Comparison> | Partial<Conjunction>
also does not work.