javascript - TypeScript:带有空对象的可区分联合
问题描述
我有以下类型User
:
type User = {
name: string;
email: string;
} | {};
所以本质上,用户可以是具有名称和电子邮件属性的对象,也可以是空对象。
当我尝试检查给定用户对象是两个中的哪一个时,TypeScript 显示错误。
if (user.name) { // ERROR
// do something if user object is populated
}
具体来说,上面的代码会引发错误:
Property 'url' does not exist on type 'PrismicImage'.
Property 'url' does not exist on type '{}'
是否可以有一个有区别的联合,其中一个接口是空对象?
解决方案
你可以给我们in
https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-the-in-operator
if (user.name) { // error
user // typeof user is User | {}
user.name // error
user.email // error
}
if ('name' in user) {
user // ok, typeof user is User
user.name // string
user.email // string
}
推荐阅读
- eos - 什么是正确的cmd。EOS cmd 的行调用。“克莱奥斯定契约?”
- javascript - 为什么 Web 服务不能正确返回字符串?
- c# - 如何将属性与 DataGrid 中的复选框绑定?
- apache - 如何在 Apache Knox 中启用 SSO?
- python - 在python中正确分配数据结构
- fortran - 无论如何检查矩阵行中的n个项在fortran中是否相等?
- azure - 应用服务 HTTP/2 不工作
- python - 带有链式比较的 PyCharm 输入警告
- ros - 如何查看所有当前使用的包?
- node.js - 在 docker 镜像中运行 npm test 并退出