首页 > 解决方案 > 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 '{}'

是否可以有一个有区别的联合,其中一个接口是空对象?

标签: javascripttypescriptdiscriminated-union

解决方案


你可以给我们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
}

tsplayground


推荐阅读