通用类的条件类型属性
为什么这不起作用?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
!
运算符作为user
的后缀:但我不建议这样做,因为您将丢失打字稿检查。
最好使用 ClientUser | null 联合,您需要进行一些 null 检查,但您将保持代码类型的安全。
You could use the
!
operator as suffix ofuser
: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.