![](/img/trans.png)
[英]TypeScript: ReturnType -> How to set the return type of function returned by a function
[英]How to make a function inherit the return type of the returned function?
我有一個函數,它接收一個函數並從react-redux
返回useSelector
鈎子的結果。
如何在我的包裝函數中使用useSelector
的返回類型?
import { shallowEqual, useSelector } from 'react-redux';
type SelectorFunction = (state: AppState) => /* TypeOfReturn */;
export default (selector: SelectorFunction) => useSelector(selector, shallowEqual);
現在我的函數返回any
,我想避免做這樣的事情
const user = useShallowEqualSelector(state => state.userAuth.user) as User | null;
如果我只使用useSelector
,則user
類型確實是User | null
User | null
const user = useSelector((state: AppState) => state.userAuth.user);
所以,這里的想法是有一個固定的狀態類型( AppState
),但選擇器函數的返回類型根據選擇器函數本身而變化——作為參數傳遞
在這種情況下,您可以使用參數化類型:
export default <TReturn>(selector: (state: AppState) => TReturn) => useSelector<AppState, TReturn>(selector, shallowEqual)
有了這個,打字稿可以根據您作為selector
函數參數傳遞的useSelector
自動推斷useSelector
的返回類型。 這與“使用 useSelector 的返回類型”不同,因為useSelector
本身具有參數化的返回類型,而我們只是將返回類型推遲到高階函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.