【发布时间】:2021-01-04 09:07:02
【问题描述】:
我从一个 API 调用中得到一个 json 响应(稍后会变成一个对象),我可以使用 queryparams 动态限制某些字段。
我已经输入了完整的回复。
现在我想要实现的是创建一个类型,它接受我给定的字段并返回一个对象类型,它只包含给定的属性。
我知道有像 Pick 这样的实用程序类型,但它们不适用于嵌套对象。
示例:
interface ResponseInterface {
a: {
a: {
a: number;
b: string;
};
b: {
a: string;
b: boolean;
};
};
b: {
a: object | null;
b: string;
}[];
}
const filters = ['a.a.a', 'a.b.b', 'b.a']; //nested properties seperated by dots
const fakeFullResponse: ResponseInterface = { //calling the api without any filters
a: {
a: {
a: 123,
b: 'aab',
},
b: {
a: 'aba',
b: true,
},
},
b: [
{
a: null,
b: 'array bb',
},
{
a: {},
b: 'array bb',
},
],
};
interface ExpectedType { //after applying those filters to the object
a: {
a: {
a: number;
};
b: {
b: boolean;
};
};
b: {
a: null | object
}[];
}
const fakeFilteredResponse: ExpectedType = { //calling the api with those fields above would get me this
a: {
a: {
a: 123,
},
b: {
b: true,
},
},
b: [
{
a: null,
},
{
a: {},
},
],
};
在给定ResponseInterface 接口和filters 的情况下,有没有办法动态创建ExpectedType 接口?如果需要,可以更改 filters 数组的格式,只要嵌套结构保持不变
【问题讨论】:
标签: typescript typescript-typings mapped-types