通用类的条件类型属性

发布于 2025-01-17 07:59:14 字数 435 浏览 2 评论 0原文

为什么这不起作用?

export class Client<isReady extends boolean = false> {
  user: isReady extends true ? ClientUser : null = null
}

Deno 抛出此错误 类型 'null' 不可分配给类型 'isReady extends true ?客户端用户:null'.deno-ts(2322) 在用户属性上,

我希望 user 属性在某些地方仅属于 null 类型,并且在某些地方仅属于 ClientUser 类型,我也希望将其初始化为 null 值。

why does this not work??

export class Client<isReady extends boolean = false> {
  user: isReady extends true ? ClientUser : null = null
}

Deno throws this error Type 'null' is not assignable to type 'isReady extends true ? ClientUser : null'.deno-ts(2322)
on the user property

I want the user property to be only of type null at some places and only of type ClientUser at some places and I also want it to be initialized with the value as null.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

夏天碎花小短裙 2025-01-24 07:59:14

您可以使用 ! 运算符作为 user 的后缀:

export class Client {
  user!: ClientUser
}

但我不建议这样做,因为您将丢失打字稿检查。

最好使用 ClientUser | null 联合,您需要进行一些 null 检查,但您将保持代码类型的安全。

You could use the ! operator as suffix of user:

export class Client {
  user!: ClientUser
}

But I do not recommend this because you will lose typescript checks.

It is better to use ClientUser | null union, you need the do some null check, but you will keep your code type safe.

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