gpt4 book ai didi

json - 如何定义 JSON 兼容参数以避免错误 "Index signature is missing"?

转载 作者:行者123 更新时间:2023-12-05 03:48:24 26 4
gpt4 key购买 nike

我有一个函数定义为:

export function useSubmitHandler(url: string, data: Json): [FormEventHandler<HTMLFormElement>, boolean] {}

Json 是:

type JsonPrimitive = string | number | boolean | null | undefined
interface JsonMap extends Record<string, JsonPrimitive | JsonArray | JsonMap> {}
interface JsonArray extends Array<JsonPrimitive | JsonArray | JsonMap> {}
export type Json = JsonPrimitive | JsonMap | JsonArray

如果我尝试使用任意接口(interface)调用它,则会出现错误:

TS2345: Argument of type 'Fee' is not assignable to parameter of type 'Json'.   
Type 'Fee' is not assignable to type 'JsonMap'.     
Index signature is missing in type 'Fee'

enter image description here

但如果我用同一个对象调用它但像 {...store.data} 那样传播,那么错误就会消失。

如何正确输入 useSubmitHandler 以便它接受任何可 JSON 字符串化的对象?

我认为 Json 类型是正确的,但它需要更多的东西来允许将任意类型传递给函数。


费用是:

interface Fee {
id: number|null;
name: string;
type: string;
amount: string;
default: number;
company_id: number;
deleted_at?: any;
active: number;
fee_or_discount: string;
}

当然,我希望它适用于任何类型。

最佳答案

方案一:重新定义Json类型

type JsonPrimitive = string | number | boolean | null;
type JsonMap = {
[key: string]: JsonPrimitive | JsonMap | JsonArray;
}
type JsonArray = Array<JsonPrimitive | JsonMap | JsonArray>;
type Json = JsonPrimitive | JsonMap | JsonArray;

方案二:在Fee接口(interface)添加索引签名

interface Fee {
[property: string]: any;
id: number|null;
name: string;
type: string;
amount: string;
default: number;
company_id: number;
deleted_at?: any;
active: number;
fee_or_discount: string;
}

方案三:为索引签名添加内联类型断言,例如:

useSubmitHandler(Router.route('fees.store')!, store.data as {[property: string]: any})

另见

TypeScript GitHub 问题 Please provide a json basic type #1897

关于json - 如何定义 JSON 兼容参数以避免错误 "Index signature is missing"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64407723/

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