gpt4 book ai didi

angular - typescript /Angular 12 : cast custom object into params-object

转载 作者:行者123 更新时间:2023-12-05 02:41:38 26 4
gpt4 key购买 nike

我想使用 HttpParamsOptionsfromObject 键将自定义对象转换为参数对象。

这个有效:

foo(): void {
const testObject = {
id: 123;
name: 'test';
someExample: 'test';
}
const httpParams = new HttpParams({ fromObject: testObject });
...
}

这行不通:

export interface SearchParams {
id: number;
name: string;
someExample: string;
}

foo(testObject: SearchParams): void {
const httpParams = new HttpParams({ fromObject: testObject });
...
}
如果我定义对象类型,

fromObject 将不起作用。

错误:TS2322:类型“SearchParams”不可分配给类型“{ [param: string]: string |编号 | bool |只读(字符串 | 数字 | bool 值)[]; }'。 “SearchParams”类型中缺少索引签名。

有什么解决办法吗?我正在使用 Angular 12。

最佳答案

最简单的方法:

   const httpParams = new HttpParams({ fromObject: {...testObject} });

错误发生是因为您的参数类型 SearchParams 与 fromObject 类型不匹配,即:

    fromObject?: {
[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
};

基本上 fromObject 参数接受任何文字对象。

因此您可以通过一些不同的方式获得相同的结果。例如……

声明文字对象(就像您所做的那样):

    const testObject = {
id: 123;
name: 'test';
someExample: 'test';
}
const httpParams = new HttpParams({ fromObject: testObject });

使用扩展运算符声明从另一个复制的对象:

    const myObject = { ...testObject };
const httpParams = new HttpParams({ fromObject: myObject });

或转换为任何类型:

   const httpParams = new HttpParams({ fromObject: testObject as any });

来自typescript doc关于 any 类型:

The any type is useful when you don’t want to write out a long typejust to convince TypeScript that a particular line of code is okay.

或者更改SearchParams 接口(interface)以与fromObject 参数类型兼容:

  export interface SearchParams {
id: number;
name: string;
someExample: string;
[param: string]: string | number;
}

foo(testObject: SearchParams): void {
const httpParams = new HttpParams({ fromObject: testObject });
}

关于angular - typescript /Angular 12 : cast custom object into params-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68040289/

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