[英]How to dynamically assign a name and type to unknown object property in Typescript
我正在使用 Shopify 的 rest 客戶端作為節點,它的請求和響應如下所示:
client.get({
path: 'orders/count.json',
query: { fulfillment_status: 'unfulfilled' }
})
{
"errors": "[API] Invalid API key or access...",
"code": 2342,
"statusText": "Authentication Error",
"Headers": "..."
}
{
"body": { "count": 8 },
"code": 2342,
"statusText": "Authentication Error",
"Headers": "..."
}
我想在這個客戶端庫上添加一些樣板,以便我可以獲得響應的類型。 這是我正在嘗試做的,但效果不太好:
const customClient = {
get: async <T, K extends string>(params: GetRequestParams) => {
const response = (await client.get(params));
if (response.body.errors) return { errors: response.body.errors };
// somehow index it. obviously not with the type declaration???
return { [K]: response.body[K] as T };
},
}
希望我可以將其用作。
const { count, error } = customClient.get<number, "count">({ ... });
任何幫助,將不勝感激。 我有一個我想利用的 Shopify API 類型的完整文件。 解決這個問題將是完美的
一個可能的實現如下所示:
const customClient = {
get: async <T, K extends string>(params: GetRequestParams):
Promise<Partial<Record<K, T> & { errors: string }>> =>
{
const response = (await client.get(params));
if (response.body.errors) return { errors: response.body.errors } as any;
return {
[Object.keys(response)[0]]: response[Object.keys(response)[0]]
} as any
},
}
正如您正確指出的那樣,在構造返回的 object 時,我們不能使用 TypeScript 泛型類型。 我們需要改用 JavaScript 功能。 在這種情況下,我只取response
的第一個鍵並將其用作返回的 object 的鍵以及索引response
object。
function 的返回類型是一個Promise
,它由以K
和T
作為鍵和值的Record
和錯誤類型組成。 我在這里使用了Partial
,因為它們都不是必需的。
現在破壞響應會導致正確的類型:
async function main(){
const { count, errors } = await customClient.get<number, "count">({} as any);
// count: number | undefined
// errors: string | undefined
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.