使用打字稿中的属性值更改接口中的属性类型?
我有一个用于在 redux-toolkit 中创建切片的接口,
interface AuthState {
authenticated: boolean;
role: number;
currentUser: IUser | null;
isAuthenticating: boolean;
}
如果 authenticated
为 true,有什么方法可以使 currentUser
始终为 IUser
吗?
因此,当访问 currentUser 时,我不必检查可能为 null
。一些解释会有所帮助,因为我是 ts
的新手
I have this interface for creating slice in redux-toolkit
interface AuthState {
authenticated: boolean;
role: number;
currentUser: IUser | null;
isAuthenticating: boolean;
}
is there any way to make currentUser
always be IUser
if authenticated
is true?
So when access currentUser I don't have to check for possibly null
. And a little explaination will help to cuz I'm new to ts
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用受歧视的联合,对
authenticated
进行歧视,然后 与公共属性相交:游乐场链接
You can use a discriminated union, discriminated on
authenticated
then intersect with the common properties:Playground Link