[英]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.