使用打字稿中的属性值更改接口中的属性类型?

发布于 2025-01-09 13:16:32 字数 381 浏览 2 评论 0原文

我有一个用于在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

¢蛋碎的人ぎ生 2025-01-16 13:16:32

您可以使用受歧视的联合,对 authenticated 进行歧视,然后 与公共属性相交

type AuthStateUnion = {
  authenticated: true;
  currentUser: IUser;
} | {
  authenticated: false;
  currentUser: null;
}

type AuthState = AuthStateUnion & {
  role: number;
  isAuthenticating: boolean;
}

let state: AuthState = Math.random() > 0.5 ? {
  authenticated: true,
  currentUser : { name: ""},
  role: 1,
  isAuthenticating: false
} :{
  authenticated: false,
  currentUser : null,
  role: 1,
  isAuthenticating: false
} 

if (state.authenticated) {
  state.currentUser.name
} else {
  state.currentUser // null
}

游乐场链接

You can use a discriminated union, discriminated on authenticated then intersect with the common properties:

type AuthStateUnion = {
  authenticated: true;
  currentUser: IUser;
} | {
  authenticated: false;
  currentUser: null;
}

type AuthState = AuthStateUnion & {
  role: number;
  isAuthenticating: boolean;
}

let state: AuthState = Math.random() > 0.5 ? {
  authenticated: true,
  currentUser : { name: ""},
  role: 1,
  isAuthenticating: false
} :{
  authenticated: false,
  currentUser : null,
  role: 1,
  isAuthenticating: false
} 

if (state.authenticated) {
  state.currentUser.name
} else {
  state.currentUser // null
}

Playground Link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文