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