gpt4 book ai didi

javascript - 使用 Typescript react Hook : Expected an assignment or function call and instead saw an expression

转载 作者:行者123 更新时间:2023-11-30 19:34:07 25 4
gpt4 key购买 nike

我成为 React 开发人员已有一段时间了。在工作中,我们现在介绍了我比较陌生的 Typescript。

我已经创建了一个使用 cookie 的钩子(Hook),但我返回的函数导致了错误。

Hook (删除了一些公司内容):

function useCookies(key: string) {
const [storedCookie, setStoredCookie] = useState(() => getCookieValue(key));

function setCookie(value: any, daysUntilExpiry?: number): any {
if (value) {
const valueToStore =
value instanceof Function ? value(storedCookie) : value;
setStoredCookie(valueToStore);

let cookieString = `${key}=${valueToStore}`;
if (daysUntilExpiry) {
const date = new Date();
date.setDate(date.getDate() + daysUntilExpiry);
cookieString = `${cookieString}; expires=${date}`;
}
document.cookie = cookieString;
}
}

return [storedCookie, setCookie];
}
const [loggedIn, setAuthState] = useCookies('logged_in');

setAuthState(true, 7);

setAuthState 函数调用给我错误 Expected an assignment or function call and instead saw an expression。谁能告诉我为什么?!

最佳答案

useCookies 的返回类型被推断为一个任意长度的数组,可以包含设置 cookie 的字符串或函数。因此,当您从列表中取出第二项时,TS 认为这可能是字符串或函数。

要解决此问题,如果您使用的是 3.4+,当您从函数返回值时,只需在返回时用 as const 标记它:

return [cookie, setCookie] as const;

编辑:Per Svensson 的上述建议也修复了它。

关于javascript - 使用 Typescript react Hook : Expected an assignment or function call and instead saw an expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125937/

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