我正在开发一个应用程序,其中我使用 redux 工具包和 localstorage 来保存主题。
我有这个片段:
import { createSlice } from "@reduxjs/toolkit";
const mode = !localStorage.getItem("theme")
? ""
: JSON.parse(localStorage.getItem("theme")); //the error is on this line
const initialState = {
mode: mode,
};
const ThemeSlice = createSlice({
name: "theme",
initialState,
reducers: {
toggleTheme: (state) => {
state.mode = state.mode === "light" ? "dark" : "light";
},
},
});
export const { toggleTheme } = ThemeSlice.actions;
export default ThemeSlice.reducer;
但它给了我一个错误:Argument of type 'string | null' is not assignable to parameter of type 'string'.
我该怎么做才能消除此错误?
问题
localStorage.getItem("theme")
返回类型为string | null
,但JSON.parse
期望为string
,因此类型不匹配。即使localStorage.getItem("theme")
在三元条件中求值 ,Typescript 也无法判断localStorage.getItem("theme")
在 falsey 分支中将求值为相同的值,它所拥有的只是getItem
返回类型string | null
。解决建议
空值合并
您可以使用 Nullish Coalescing 并简单地提供适当的
string
类型后备值来转换null
为空字符串。第一种方案
另一种方法是读取主题并将其存储
localStorage
到变量中,然后在三元表达式中使用该主题,这样类型系统在整个表达式中引用相同的值。第二种选择
或者,你可以断言该值不为空(
!
)但如果您 100% 确定
localStorage.getItem("theme")
不会返回任何null
值,那么这只是一个“逃生舱”。在这三个选项中,我推荐前两个选项,它们可以安全地保留在类型系统内。