【发布时间】:2019-07-03 14:57:20
【问题描述】:
我有一个基本的帐户界面:
interface Account {
id: number;
email: string;
password: string;
type: AccountType;
}
其中账户类型:
enum AccountType {
Foo = 'foo',
Bar = 'bar'
}
以及扩展 Account 接口的两个帐户子类型(FooAccount 和 BarAccount):
interface FooAccount extends Account {
foo: Foo;
}
interface BarAccount extends Account {
bar: Bar;
}
Account 是一个聚合,包含基本的帐户信息,并且根据类型,拥有一个 Foo 或一个 Bar 对象。
对这些对象的操作只能由其所有者(帐户)执行。
我已经定义了一个AccountRepository:
export interface AccountRepository {
findById(accountId: number): Account;
}
findById(accountId: number) 返回一个 Account,但此帐户可以是任何 FooAccount 或 BarAccount。
我想在对Foo 或Bar 执行任何操作之前使用这个findById 函数。例如,假设我要更新帐户的Foo:
- 将使用
findById(accountId: number)检索帐户 - 检查账户的AccountType,在本例中为
account.type === AccountType.Foo - 如果 AccountType 检查正确,则将访问
account.foo.id并使用该fooId执行所需的更新
这里的问题是,最后一点失败了:findById(accountId: number): Account 返回一个 Account 并且在其接口中没有定义 foo: Foo 属性。
我也尝试了以下方法,但也无法做到:
const fooAccount: FooAccount = findById(accountId);
因为该函数返回一个帐户。
我试图弄清楚如何实现这一点,我错过了什么?有什么我可能做错了吗?
【问题讨论】:
标签: javascript typescript oop