簡體   English   中英

在聯合類型上應用 ReturnType

[英]Apply ReturnType on union type

TypeScript 不能在聯合類型上使用ReturnType嗎?

type NumberParser = (input: string) => number | DiplomacyError;
type StringParser = (input: string) => string | DiplomacyError;
type Parser = NumberParser | StringParser;

export interface Schema {
  [key: string]: Parser | Schema;
}

export type RawType<T extends Schema> = {
  [Property in keyof T]: T[Property] extends Schema
    ? RawType<T[Property]>
    : ReturnType<T[Property]>; // T[Property] marked as error
};

<T[Property]>給出以下錯誤:

Type 'T[Property]' does not satisfy the constraint '(...args: any) => any'.
  Type 'T[keyof T]' is not assignable to type '(...args: any) => any'.
    Type 'T[string] | T[number] | T[symbol]' is not assignable to type '(...args: any) => any'.
      Type 'T[string]' is not assignable to type '(...args: any) => any'.
        Type 'Parser | Schema' is not assignable to type '(...args: any) => any'.
          Type 'Schema' is not assignable to type '(...args: any) => any'.
            Type 'Schema' provides no match for the signature '(...args: any): any'.ts(2344)

TypeScript 中的一個已知問題是條件類型的錯誤分支不會縮小其類型。 所以在T extends U? F<T>: G<T> T extends U? F<T>: G<T>不采用G<T>並將其替換為G<Exclude<T, U>>之類的東西。 就編譯器而言, G<T> T的 T 可能仍然可以分配給U ,即使我們很明顯它不會。 請參閱microsoft/TypeScript#29188 看起來在microsoft/TypeScript#24821上已經做了一些工作來解決這個問題,但它沒有被合並。 我不清楚這個問題是否或何時會得到解決。

在那之前,在必要時很容易(如果煩人的話)縮小自己的范圍:

export type RawType<T extends Schema> = {
    [K in keyof T]: T[K] extends Schema
    ? RawType<T[K]>
    : ReturnType<Exclude<T[K], Schema>>;
};

或者可能

export type RawType<T extends Schema> = {
    [K in keyof T]: T[K] extends Schema
    ? RawType<T[K]>
    : ReturnType<Extract<T[K], Parser>>;
};

Playground 代碼鏈接

暫無
暫無

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

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