【发布时间】:2023-02-10 15:09:22
【问题描述】:
我们有一个从 API 返回的端点,其中类型是动态的,具体取决于响应是什么。
我将如何返回调用类型并将该类型导入到文件中。
我想要达到的目标:
import * as ResponseTypes from './types'
export const request = async ({
APIURL,
apiType
}: RequestObj) => {
return await fetch(`${APIURL}/`, {
method: 'POST',
headers,
body: JSON.stringify(postBody),
})
.then((response) => response.json())
.then((responseJson) => {
// Below we need to
return Promise.resolve(Response as ResponseTypes[apiType]);
})
.catch((error) => {
console.error('Request Fetch Catch Error', error);
return Promise.reject(error);
});
}
// Example Call
const userData = await request('..api.com/user', 'UserType')
// This userData would have the response type based on the dynamic string passed through
const email = userData.email
所以导入的ResponseTypes 文件将包含所有 API 响应类型。
我只是不知道如何根据响应转换该类型,以便在响应中传回该特定响应的类型。
我将如何在打字稿中输入这个?
先谢谢了
【问题讨论】:
标签: typescript casting