示例:
function useCallback(fn) {
return fn;
}
type ApiData = {
'/user': { user: any },
'/post': { post: any },
};
function useApi<Path extends keyof ApiData>(
path: Path,
opts: {
cb?: (data: ApiData[Path]) => void,
},
) {}
useApi('/user', { cb: ({ user }) => null }); // ok
useApi('/user', { cb: ({ post }) => null }); // Property 'post' does not exist on type '{ user: any; }'
useApi('/user', { cb: useCallback(({ user }) => null) }); // ok
useApi('/user', { cb: useCallback(({ post }) => null) }); // should have error
在此示例中,没有useCallback
的情况下,TS能够自动确定回调参数的类型。但是,useCallback
会失去该功能。
有趣的是,如果我需要设置cb
属性,则TS能够推断参数的类型:
function useApi<Path extends keyof ApiData>(
path: Path,
opts: {
cb: (data: ApiData[Path]) => void, // <- removed the "?"
},
) {}
useApi('/user', { cb: useCallback(({ post }) => null) }); // Property 'post' does not exist on type '{ user: any; }'
如何让TS推断回调的参数?
答案 0 :(得分:0)
与?
可选运算符无关紧要
Typescript解析器正确推断出类型是什么。
由于您将useApi函数的第一个参数指定为'/user'
,所以它将不起作用。
将其更改为
useApi('/post', { cb: useCallback(({ post }) => null) });
那行得通。