我正在尝试编写一个接口,但它不断弹出一个错误:
"Property 'success' of type 'boolean' is not assignable to string index type 'PageableLaravel'
export interface PageableLaravel {
path: string;
current_page: number;
from: number;
}
export interface Pageable {
success: boolean; // <-"Property 'success' of type 'boolean' is not assignable to string index type 'PageableLaravel'
message: string; // "Property 'message' of type 'string' is not assignable to string index type 'PageableLaravel'
[key: string]: PageableLaravel
}
Run Code Online (Sandbox Code Playgroud)
该[key: string]会随时更改,例如:下面是从API返回的JSON的例子
{
success: true,
message: 'success',
pages: {//<-key name always will change
path: "XX"
//etc
}
}
{
success: true,
message: 'success',
products: {//<-key name always will change
path: "XX"
//etc
}
}
{
success: true,
message: 'success',
brands: {//<-key name always will change
path: "XX"
//etc
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法声明一个可能/可能不总是改变的密钥?
不幸的是,您使用的索引签名语法不允许这样做。当您添加索引签名 ( [key: string]: PageableLaravel) 时,这意味着所有属性都必须是 PageableLaravel,而不仅仅是所有未指定的属性。
您可以使用交集类型解决此问题:
export interface PageableLaravel {
path: string;
current_page: number;
from: number;
}
export type Pageable = {
success: boolean;
message: string;
} & {
[key: string]: PageableLaravel
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7485 次 |
| 最近记录: |