最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Restricting types on object properties in TypeScript dynamically based on other properties - Stack Overflow

programmeradmin4浏览0评论
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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论