在一個基本的 React 自定義鉤子中,唯一的區別是回傳[ ]or { }:
const useCustomHookSquare= () => {
const [state, setState] = useState<Type>(initialState);
return [state, storeBounceBox];
}
const useCustomHookCurly= () => {
const [state, setState] = useState<Type>(initialState);
return {state, storeBounceBox};
}
這有效:
const {state, setState} = useCustomHookCurly();
// or even
const {setState} = useCustomHookCurly();
但是在呼叫 setState 函式(或以這種方式匯出的任何其他函式)時,用方括號解構會導致 TypeScript 錯誤:
const [state, setState] = useCustomHookSquare();
setState(someState); // "This expression is not callable. Type has no call signatures".
我覺得這里缺少一些基本的 JavaScript 概念。為什么{}版本允許我呼叫函式但[]版本不允許?
uj5u.com熱心網友回復:
因為你的useCustomHookSquare鉤子沒有回傳型別資訊,TypeScript 推斷它回傳兩個不同型別的陣列。但并非可以成為該陣列一部分的兩種型別都是函式,因此您會收到型別錯誤,因為其中一個可能的值不可呼叫。
const useHook = () => {
return ["item", () => true]
}
// The inferred value of useHook is now
//
// (string | (() => boolean))[]
//
// So when calling `fn`, TypeScript doesn't know if it will be a string or a function
const [item, fn] = useHook()
//This expression is not callable.
// Not all constituents of type 'string | (() => boolean)' are callable.
// Type 'string' has no call signatures.
fn()
向您的函式添加一些回傳型別以useCustomHookSquare解決問題。這是我的固定示例的樣子。
const useHook = (): [string, () => true] => {
return ["item", () => true]
}
TypeScript 現在知道回傳的陣列中只有 2 個專案,并且這些專案的型別應該始終相同。
uj5u.com熱心網友回復:
默認情況下,打字稿將更廣泛的型別分配給陣列。因此,如果您有:
const arr = ["str", 5];
型別將是 的陣列(string | number)[],而不是 的元組[string, number]。
要使其成為元組,請使用as const:
const useCustomHookSquare= () => {
const [state, setState] = React.useState<string>();
return [state, setState] as const;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/471276.html
下一篇:使用映射型別生成元組型別
