gpt4 book ai didi

TypeScript:输入递归类型

转载 作者:行者123 更新时间:2023-12-03 16:45:55 24 4
gpt4 key购买 nike

我有一个基于用户输入在客户端生成的查询,如下所示。

const query = {
"or": [
{
"field": "username",
"operator": "in",
"value": [
"jdoe",
"jsmith"
]
},
{
"and": [
{
"field": "email",
"operator": "matches",
"value": "/^gmail.com/"
},
{
"or": [
{
"field": "last_sign_in",
"operator": "lt",
"value": 1599619454323
},
{
"field": "last_sign_in",
"operator": "gt",
"value": 1489613454395
}
]
}
]
}
]
}

但是,为了将其迁移到简洁的 typescript 表示形式,我正在努力使其按照我想要的方式工作。

我有这些定义:


type Operator = 'eq' | 'in' | 'matches' | 'lt' | 'gt';
type Condition = 'and' | 'or' | 'not';

interface SimpleQuery {
field: string;
operator: Operator;
value: any;
}

interface Query {
condition: SimpleQuery[] // here I want `condition` to come from the type Condition
// I have tried these solutions involving [{ x of y }] https://github.com/microsoft/TypeScript/issues/24220
}

以下是我从 TS 编译器得到的错误:

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
Cannot find name 'key'.
'Condition' only refers to a type, but is being used as a value here.

我已经尝试过这个

type Query = {
[key in Condition]: SimpleQuery[];
}

通过这种方法, typescript 也希望我添加所有缺少的条件。

最佳答案

我认为这将是描述您所描述的对象的最准确的类型::

type Operator = 'eq' | 'in' | 'matches' | 'lt' | 'gt';

type UnionKeys<T> = T extends T ? keyof T : never;
type Condition = UnionKeys<OperatorExpression>;

interface FieldCondition {
field: string;
operator: Operator;
value: any;
}

type BinaryExpression<T extends PropertyKey> = {
[P in T] : [FieldCondition | OperatorExpression, FieldCondition | OperatorExpression]
}
type UnaryExpression<T extends PropertyKey> = {
[P in T] : [FieldCondition | OperatorExpression]
}

type OperatorExpression = BinaryExpression<"and"> | BinaryExpression<"or"> | UnaryExpression<"not">


const query: OperatorExpression = {
"or": [
{
"field": "username",
"operator": "in",
"value": [
"jdoe",
"jsmith"
]
},
{
"and": [
{
"field": "email",
"operator": "matches",
"value": "/^gmail.com/"
},
{
"or": [
{
"field": "last_sign_in",
"operator": "lt",
"value": 1599619454323
},
{
"field": "last_sign_in",
"operator": "gt",
"value": 1489613454395
}
]
}
]
}
]
}

Playground Link

此版本强制执行逻辑运算符的正确数量(使用元组类型),并根据运算符并集派生出条件并集。

关于TypeScript:输入递归类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61833395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com