【问题标题】:Conditional return type extending undefined扩展未定义的条件返回类型
【发布时间】:2023-04-04 14:53:01
【问题描述】:

我正在创建一个用于处理 API 响应的实用程序,我希望避免消费者在指定泛型类型时必须检查未定义:

export async function createAPIResponse<T = undefined>(
    request: Request,
    response: Response
): Promise<T extends undefined ? undefined : T> {
    if (response.status === 204) {
        return;
    }

    if (!response.ok) {
        try {
            throw new APIError(request, response, await response.json());
        } catch {
            throw new HTTPError(request, response);
        }
    }

    return response.json();
}

TypeScript 给我以下错误:

类型 'undefined' 不能分配给类型 'T extends undefined ?未定义:T'。 ts(2322)

我的目标是能够像这样使用该功能:

// No response expected and no generic passed to function
try {
    await createAPIResponse(putRequest, responseWithStatus204AndNoBody);
} catch (error) {
    console.error(error);
}

// Response of type SomeType expected
try {
    const jsonData = await createAPIResponse<SomeType>(getRequest, responseWithStatus200AndJSONBody);
    console.log(jsonData);
} catch (error) {
    console.error(error);
}

我已经四处寻找一些可能的解决方案(例如How to do a conditional generic type that has a value when it is undefined but not when it is undefined AND another thing),但我还没有找到一个不会产生错误的解决方案。

【问题讨论】:

  • 你需要一个类型断言来实现。
  • 我不明白你的意思,你能举个例子吗?
  • 他的意思是:obj as ExpectedType。无论如何,你为什么不直接使用 T=unknown 并返回 Promise
  • @tokland 声明 T = unknown 在尝试从状态条件 (typescriptlang.org/play?#code/…) 中返回时仍然给我相同的原始 2322 错误

标签: typescript typescript-generics


【解决方案1】:

我对@9​​87654321@ 建议的解决方案感到满意,我最终实施如下:

type OptionalReturn<T> = T extends undefined ? void : T;

export async function createAPIResponse<T = undefined>(
    request: Request,
    response: Response
): Promise<OptionalReturn<T>> {
    // No content
    if (response.status === 204) {
        return undefined as OptionalReturn<T>;
    }
    
    ...
}

【讨论】:

    猜你喜欢
    • 2020-05-26
    • 2011-07-16
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多