gpt4 book ai didi

typescript 从返回回调函数值创建一个动态元组

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:31 26 4
gpt4 key购买 nike

我有以下功能:

    class A<S> {
data?: S;

getSomething<R extends ((data: S) => R)>(...funcs: ((data: S) => R)[]): ReturnType<R>[] {
return <any>funcs.map(f => {
return f(this.data as S);
});
}
}

const a = new A<{ id: number, name: string }>();
const arr = a.getSomething(data => data.name, data => data.id);

值的类型是unknown[]。如何根据返回的回调值将其更改为动态的?因此,在上述情况下,我希望类型为 [number, string]。

最佳答案

首先,您的类型参数应该是这些函数的数组。这将使您能够将传入的箭头函数的类型捕获为函数元组。然后我们可以使用映射类型将元组映射到适当的返回类型。

type ReturnTypes<T extends Array<(...a: any[]) => any>> = {
[P in keyof T]: T[P] extends (...a: any[]) => infer R ? R : never
}
class A<S> {
data?: S;

getSomething<R extends Array<((data: S) => any)>>(...funcs: R): ReturnTypes<R> {
return <any>funcs.map(f => {
return f(this.data as S);
});
}
}

const a = new A<{ id: number, name: string }>();
const arr = a.getSomething(data => data.name, data => data.id); //[string, number]

编辑

您也可以使用数组作为参数,但您需要稍微更改约束以使编译器推断出元组类型:

type ReturnTypes<T extends Array<(...a: any[]) => any>> = {
[P in keyof T]: T[P] extends (...a: any[]) => infer R ? R : never
}
class A<S> {
data?: S;

getSomething<R extends [(data: S) => any] | Array<(data: S) => any>>(funcs: R): ReturnTypes<R> {
return <any>funcs.map(f => {
return f(this.data as S);
});
}
}

const a = new A<{ id: number, name: string }>();
const arr = a.getSomething([data => data.name, data => data.id]); //[string, number]

关于 typescript 从返回回调函数值创建一个动态元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956918/

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