gpt4 book ai didi

typescript - 如何修复泛型 TypeScript 函数以返回有效的推断类型?

转载 作者:行者123 更新时间:2023-12-04 04:23:25 25 4
gpt4 key购买 nike

我有以下 TypeScript 代码 ( link to playground ):

type MyCallback<T> = (s: string, payload: T) => void;

interface IActions {
do1: MyCallback<number>;
do2: MyCallback<string>;
[key: string]: (s: string, payload: any) => void;
}

function convert<T extends { [key: string]: (s: string, payload: any) => void }>(callbackMap: T) {

const result: { [key: string]: <U>(payload: U) => void } = {};

Object.keys(callbackMap).forEach(key => {
if (typeof callbackMap[key] === 'function') {
result[key] = callbackMap[key].bind(null, "data");
}
})

return result;
}

const maps = convert<IActions>({
do1: (s: string, payload: number) => {
//
},
do2(s: string, payload: string) {
//
}
});

maps.do1(1); // valid
maps.smth("1"); // should be type-check error, but TS thinks it's valid

我想做的是创建一个函数,它通过接口(interface)接受一个对象。该函数将所有方法从对象转换为一个新对象,其中所有方法都有一个固定参数(通过 bind 方法)。也就是说,我要转换这个接口(interface)

interface IActions {
do1: (state: string, payload: number);
do2: (state: string, payload: string);
.....
}

interface IActions {
do1: (payload: number);
do2: (payload: string);
....
}

我想让它成为通用的,所以它会根据通用参数转换任何接口(interface)。

我当前方法的问题是我没有对我的 maps 对象进行任何智能感知和类型检查。

是否可以修改我的 convert 函数,使返回类型由传入接口(interface)自动推断?换句话说,我对返回值进行了完整的类型检查和智能感知(在我的例子中是 maps)。

最佳答案

maps.smth 有效的事实是由于结果上的显式索引签名。您在这里需要的是一个映射类型,用于将 IActions 的属性映射到包含修改后的方法的新类型。要创建新的方法签名,我们可以使用条件类型来提取其余参数(跳过第一个)

type MyCallback<T> = (s: string, payload: T) => void;

interface IActions {
do1: MyCallback<number>;
do2: MyCallback<string>;
}

function convert<T extends Record<keyof T, (s: string, payload: any) => void>>(callbackMap: T) {

const result: Record<string, (...a: any[]) => any> = {}

Object.keys(callbackMap).forEach(key => {
if (typeof callbackMap[key as keyof T] === 'function') {
result[key] = callbackMap[key as keyof T].bind(null, "data");
}
})

return result as {
[P in keyof T]: T[P] extends (s: string, ...p: infer P) => infer R ? (...p: P) => R : never;
};
}

const maps = convert<IActions>({
do1: (s: string, payload: number) => {
//
},
do2(s: string, payload: string) {
//
}
});

maps.do1(1); // valid
maps.do1("1"); //err
maps.smth("1"); // should be type-check error, but TS thinks it's valid

Play

关于typescript - 如何修复泛型 TypeScript 函数以返回有效的推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536688/

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