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
1 Answer
Reset to default 8Yeah, 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
本文标签:
版权声明:本文标题:javascript - Restricting types on object properties in TypeScript dynamically based on other properties - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744326764a2600765.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论