[英]Restricting types on object properties in TypeScript dynamically based on other properties
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?有没有更好的方法来限制基于
field
使用 Typescript 的value
类型,如下所述?
const adultCriteria: Criteria<User> = {
field: "age",
operator: ">",
value: 18
}
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 composite of 3 possible types:这样,您将获得 3 种可能类型的联合类型组合:
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: ">"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.