如何声明变为A类或B的时候一个延伸的其他稿

0

的问题

我有一个上下文中提供者的流用户数据在整个应用程序。

我有一个学生接口:

export interface Student extends User

我会喜欢的提供者返回的用户数据的类型 StudentUser 如下:

let userData: Student | User = null;

在试图访问了酒店只提供给学生, userData?.currentTeamVS代码发送以下错误:

Property 'currentTeam' does not exist on type 'Student | User'.
  Property 'currentTeam' does not exist on type 'User'.ts(2339)

我需要帮助找出为什么它被默认为父母的接口以及如何允许的选择两者。

1

最好的答案

1

这是标准的行为的工会:除非你做些检查是什么类型你处理,稿只会让你的访问特性上存在的 所有 成员联盟。

这里是一些例子可以如何缩小的类型。 你可以检查,如果该财产的存在:

if ('currentTeam' in userData) {
  console.log(userData.currentTeam);
}

或如果你已经创造了类(其中可能没有),可以用实例:

if (userData instanceof Student) {
  console.log(userData.currentTeam);
}

或者,你可以改变的类型,因此它们都具有一个酒店的共同点,然后你就可以检查看看有什么类型的你处理。 有时这被称为"歧视联盟"。

interface User {
  type: 'user',
  // rest of the type here
}

interface Student extends User {
  type: 'student',
  currentTeam: // something,
  // rest of the type here
}

if (userData.type === 'student') {
  console.log(userData.currentTeam);
}
2021-11-24 00:11:30

谢谢你。 我能够使用这种设置上的默认值的形式领域的三元: 'currentTeam' in userData ? userData.currentTeam.teamName: 'No Team Set'
Rafael Zasas

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................