簡體   English   中英

TypeScript 推斷不適用於嵌套 generics,推斷類型為未知

[英]TypeScript inference not working on nested generics, infers type as unknown

我需要 TypeScript 才能在我的“wrongInference”function 的返回值中正確推斷類型 T。

interface Foo {
  bar: string;
}

const paramFunction = (bar: string): Foo => ({
  bar
});

type GenericFunction<T> = (...args: any) => T;

export const wrongInference = <T, F extends GenericFunction<T>>(
  paramFunction: F
) => ({
  data: {} as T,
});

const wrongType = wrongInference(paramFunction);

TypeScript 將data值推斷為未知。 有沒有辦法解決?

在此處輸入圖像描述

以下是如何使用條件返回類型和infer關鍵字解決問題:

interface Foo {
    bar: string;
}

const paramFunction = (bar: string): Foo => ({
    bar
});

type GenericFunction<T> = (...args: any) => T;

export const wrongInference = <F extends GenericFunction<any>>(
    paramFunction: F
): F extends GenericFunction<infer T> ? { data: T } : never => ({
    data: {},
} as any);

const wrongType = wrongInference(paramFunction);

TypeScript 操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM