在我的 React 应用程序中,我使用非空断言 (!) 来告诉 TS 来自useContext钩子的值不为空。它运行良好,似乎是非空断言的教科书用例,但根据推荐的 eslint 规则,非空断言是一个警告。
作为 TypeScript 的新手,我想确保在处理这些情况时不会错过通用模式或最佳实践方法。或者也许有不同的方式来键入user下面示例中的对象。
// context.ts
interface State {
user: User | null; // User type is defined elsewhere, has 'id' and 'email'
}
const state: State = {
user: null,
};
Run Code Online (Sandbox Code Playgroud)
state.user。// App.tsx
return state.user ? <Dashboard /> : <Login />;
Run Code Online (Sandbox Code Playgroud)
state.user,但我仍然看到以下错误。// Dashboard.tsx
const { state } = React.useContext(context);
const name = state.user.firstName; // Object is possibly 'null'. …Run Code Online (Sandbox Code Playgroud)