[英]Is there a way to build a type interface with dynamic field name?
I want to build a type around the lines of:我想围绕以下行构建一个类型:
interface Type<ofWhat>'fieldName'{
fieldName: ofWhat[];
otherProps: any;
}
Because the API endpoint has this weird design.因为 API 端点有这种奇怪的设计。
I've tried to do something like this:我试图做这样的事情:
type Page<T> = {pageInfo: PageInfo} | {[key:string]: Array<T>}
In which can subscribe to objects like:其中可以订阅对象,例如:
const obj2:Page<Card> = {
pageInfo: {
totalItens: 0,
totalPages: 0,
pageNumber: 0,
lastPage: true
},
cards: [
{
header: "string",
title: "string",
content: "string",
lawsuitId: "3fa85f64-5717-4562-b3fc-2c963f66afa6"
},
]
}
However, this is problematic for the linter that doesn't understand that cards
is a dynamic name and mark as an error.但是,这对于不理解
cards
是动态名称并标记为错误的 linter 来说是有问题的。
Any ideas to improve this interface design?有什么想法可以改进这个界面设计吗? Thanks!
谢谢!
Using Record<>
with a constrained type for the key seems to check out ...将
Record<>
与键的约束类型一起使用似乎可以检查...
type BasePage = { pageInfo: PageInfo };
type Page<Key extends string, Type> = BasePage & Record<Key, Type[]>;
interface Card {
header: string;
title: string;
content: string;
lawsuitId: string;
}
interface PageInfo {
totalItens: number;
totalPages: number;
pageNumber: number;
lastPage: boolean;
}
type CardPage = Page<"cards", Card>;
const obj2: CardPage = {
pageInfo: {
totalItens: 0,
totalPages: 0,
pageNumber: 0,
lastPage: true,
},
cards: [
{
header: "string",
title: "string",
content: "string",
lawsuitId: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
},
],
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.