gpt4 book ai didi

javascript - TypeScript:接口(interface)多态性问题

转载 作者:行者123 更新时间:2023-12-05 06:28:10 26 4
gpt4 key购买 nike

我有一个基本帐户界面:

interface Account {
id: number;
email: string;
password: string;
type: AccountType;
}

其中账户类型:

enum AccountType {
Foo = 'foo',
Bar = 'bar'
}

和扩展 Account 接口(interface)的两个帐户子类型(FooAccountBarAccount):

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,但这个帐户可以是任何 FooAccountBarAccount.

我想在对 FooBar 执行任何操作之前使用此 findById 函数。例如,假设我想更新帐户的 Foo:

  • 将使用 findById(accountId: number) 检索帐户
  • 检查帐户的 AccountType,在本例中为 account.type === AccountType.Foo
  • 如果 AccountType 检查正确,则将访问 account.foo.id 并使用该 fooId 执行所需的更新

这里的问题是,最后一点失败了:因为 findById(accountId: number): Account 返回一个 Account 而没有 foo:在其接口(interface)中定义的 Foo 属性。

我也试过下面的方法,但是也做不到:

const fooAccount: FooAccount = findById(accountId);

因为该函数返回一个帐户

我想弄清楚如何实现这一点,我错过了什么?有什么我可能做错的吗?

最佳答案

最好的解决方案可能是使用可区分的联合。

export class Bar { public idBar: number; }
class Foo { public idFoo: number; }
interface AccountCommon {
id: number;
email: string;
password: string;
}

enum AccountType {
Foo = 'foo',
Bar = 'bar'
}

interface FooAccount extends AccountCommon {
type: AccountType.Foo; // type can only be Foo
foo: Foo;
}
interface BarAccount extends AccountCommon {
type: AccountType.Bar; // type can only be Bar
bar: Bar;
}
// The discriminated union
type Account = BarAccount | FooAccount //type is common so type can be either Foo or Bar

export interface AccountRepository {
findById(accountId: number): Account;
}

let r: AccountRepository;

let a = r.findById(0);
if (a.type === AccountType.Bar) { // type guard
a.bar.idBar // a is now BarAccount
} else {
a.foo.idFoo // a is now FooAccount
}

关于javascript - TypeScript:接口(interface)多态性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54608124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com