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