admin管理员组

文章数量:1402544

type MatchOperator = "==" | ">" | "<";

type Criteria<T, P extends keyof T> = {
    field: P,
    value: T[P],
    operator: MatchOperator,
}

interface User {
    name: string;
    age: number;
    id: number;
}

const adultCriteria: Criteria<User, "age"> = {
    field: "age",
    operator: ">",
    value: 18
}

Is there a better way to restrict the type of value based on field using Typescript as mentioned below?

const adultCriteria: Criteria<User> = {
    field: "age",
    operator: ">",
    value: 18
}
type MatchOperator = "==" | ">" | "<";

type Criteria<T, P extends keyof T> = {
    field: P,
    value: T[P],
    operator: MatchOperator,
}

interface User {
    name: string;
    age: number;
    id: number;
}

const adultCriteria: Criteria<User, "age"> = {
    field: "age",
    operator: ">",
    value: 18
}

Is there a better way to restrict the type of value based on field using Typescript as mentioned below?

const adultCriteria: Criteria<User> = {
    field: "age",
    operator: ">",
    value: 18
}
Share Improve this question edited Apr 28, 2020 at 8:48 Mikko Ohtamaa 84k61 gold badges287 silver badges468 bronze badges asked Apr 28, 2020 at 8:44 TamilTamil 5,3589 gold badges43 silver badges61 bronze badges 2
  • I think TypeScript typing concerns only types themselves. Values are something that is handled runtime, and type checks are handled during the pilation phase. They are two different problems. If you want to have an input validation for your ining objects, you can use a library like falidator npmjs./package/@codeallnight/falidator - But if there is a good use case and way to do like you describe it in a question that would be interesting. – Mikko Ohtamaa Commented Apr 28, 2020 at 8:50
  • The type looks good. Best you could do is to try having the second type parameter inferred from the definition of the object. – Bergi Commented Apr 28, 2020 at 8:51
Add a ment  | 

1 Answer 1

Reset to default 8

Yeah, it's possible:

type Criteria<T> = {
    [P in keyof T]: {
        field: P,
        value: T[P],
        operator: MatchOperator
    }
}[keyof T]

This way you get a union type posite of 3 possible types:

type OnePossibleCriteria = Criteria<User>

type OnePossibleCriteria = {
    field: "name";
    value: string;
    operator: MatchOperator;
} | {
    field: "age";
    value: number;
    operator: MatchOperator;
} | {
    field: "id";
    value: number;
    operator: MatchOperator;
}

And when you assign a solid value to it, it's narrowed down to one of them.

const adultCriteria: OnePossibleCriteria = {
    field: "age",
    value: 18,
    operator: ">"
}

TypeScript Playground

本文标签: