gpt4 book ai didi

typescript 仅从重载中选择特定方法(要传递给 Parameters)

转载 作者:行者123 更新时间:2023-12-04 17:15:20 24 4
gpt4 key购买 nike

背景
所以我在从重载的函数中获取特定参数时遇到问题。例如:

// someLib.d.ts
type Component<T> = {};
type A = {};
type B = {};
type C = {};
type Opts = {};
type ModernOpts = {};

export declare function mount(component: A, options: Opts): Component<A>;
export declare function mount(component: B, options: Opts): Component<B>;
export declare function mount(component: C, options: ModernOpts): Component<C>;
问题是,不知何故,如果我在另一个文件上这样做:
import { mount } from 'someLib';

type specificMountParams = Parameters<typeof mount>;
我得到的参数是 [C, ModernOpts] ,而且好像没有办法得到 [A, Opts]的参数, 或 [B, Opts] .
问题
有什么办法可以找回 具体 来自重载函数的参数? (所以我可以得到 [A, Opts] 参数)
限制和信息
那些类型 (A, B, Opts)不是由库导出的,我需要创建一个需要这种类型的函数来做类似的事情。

最佳答案

来自 docs :

When inferring from a type with multiple call signatures (such as the type of an overloaded function), inferences are made from the last signature (which, presumably, is the most permissive catch-all case). It is not possible to perform overload resolution based on a list of argument types.


考虑这个例子:
function foo(a: number): number
function foo(a: string): string // last signature
function foo(a: number | string): number | string {
return null as any
}

type Fn = typeof foo

// returns last overloaded signature
type Arguments = Parameters<Fn> // [a: string]
Parameters总是返回最后重载的函数签名。
尝试更改顺序:
function foo(a: string): string 
function foo(a: number): number// last signature
function foo(a: number | string): number | string {
return null as any
}

type Fn = typeof foo

// returns last overloaded signature
type Arguments = Parameters<Fn> // [a: number]
没有办法返回所有参数的联合,因为它是不合理的。
看官方解释 here

It's not really possible to make this in a way that's both useful and sound. Consider a function like

declare function fn(n1: number, n2: number): void;

declare function doCall<T extends (a1: any, a2: any) => void>(func: T,
a0: Parameters<T>[0], a1: Parameters<T>[1]): void; ```


If Parameters<T>[0] returns string | number, then doCall(fn, 0, "")would incorrectly succeed. If Parameters<T>[0]> returns string & number, then doCall(fn, 0, 0) would incorrectly fail (and be a bigbreaking change). Notably, with conditional types and unions, reallythe only kind of functions that can't be typed with a single overloadare exactly the ones that have this failure mode.


当前的行为至少使某些调用被正确接受。
您可以在上面的 github 线程中找到一些解决方法

关于 typescript 仅从重载中选择特定方法(要传递给 Parameters<T>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68799234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com