【问题标题】:Typescript How to cast a type of a string as a name打字稿如何将字符串类型转换为名称
【发布时间】: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


    【解决方案1】:

    也许添加一个接口并使用泛型类型:

    import * as ResponseTypes from './types';
    interface RequestObj<T extends keyof ResponseTypes> {
      APIURL: string;
      apiType: T;
    }
    export const request = async <T extends keyof ResponseTypes>({
      APIURL,
      apiType
    }: RequestObj<T>) => {
      return await fetch(`${APIURL}/`, {
        method: 'POST',
        headers,
        body: JSON.stringify(postBody),
      })
        .then((response) => response.json())
        .then((responseJson) => {
          return Promise.resolve(responseJson as ResponseTypes[T]);
        })
        .catch((error) => {
          console.error('Request Fetch Catch Error', error);
          return Promise.reject(error);
        });
    };
    
    const userData = await request<'UserType'>({ APIURL: '..api.com/user', apiType: 'UserType' });
    const email = userData.email;
    

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2020-11-21
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多