'How can I determine the type of another property of same object according to the property's value of the object?

I have the types as follows:

type Operators =
    | "eq"
    | "ne"
    | "lt"
    | "gt"
    | "lte"
    | "gte"
    | "in"
    | "nin"
    | "contains"
    | "ncontains"
    | "containss"
    | "ncontainss"
    | "between"
    | "nbetween"
    | "null"
    | "nnull"
    | "or"

type Filter = {
    field: string;
    operator: Operators;
    value: any
};

export type Filters = Filter[];

What I am trying to do is define the Filter type by the Operators type.

If the user specifies Operators as "or" then the field property is not required and the value property is Filters type. As follows:

export type Filter = {
    field: string | undefined;
    operator: Operators;
    value: Filters;
};

If the user specifies Operators other than "or" then the field property is required and the value property is any type. As follows:

export type Filter = {
    field: string;
    operator: Operators;
    value: any
};

How can I determine the type of another property of same object according to the property's value of the object?



Solution 1:[1]

If you use Enums you can make field required if the Operator equals Or.

enum Operators {
  Eq = "eq",
  Ne = "ne",
  Or = "or"
}

type Filter = {
    field: string;
    operator: Operators.Or;
    value: any
} | type Filter = {
    field: string;
    operator: Operators.Or;
    value: any
} | {
    field?: string;
    operator: Exclude<Operators, Operators.Or>
    value: any
};

// field is required
const filterOr: Filter = {
    field: 'field', 
    value: 'string',
    operator: Operators.Or
}

// field is not required
const filterEq: Filter = {
    value: 'string',
    operator: Operators.Eq
}

const filterEe: Filter = {
    value: 'string',
    operator: Operators.Ne
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1