使用接口作为类的键

问题描述 投票:0回答:1

我有一个问题:

我有这样的课程:

export class BankAccount {
  id: number;
  label?: string;
  type: AccountTypes;

  constructor(init?: Partial<BankAccount>) {
    Object.assign(this, init);
  }
}

对吗? AccountTypes在哪里:

enum AccountTypes {
  CHECKING = 'Checking',
  SAVINGS = 'Savings',
}

为什么要尝试做类似的事情:

const account = {
      id: 1,
      label: 'John Doe: Chase Checking ****1892',
      type: 'CHECKING',
}
const something = new BankAccount(account)

我收到以下错误:

Types of property 'type' are incompatible.
        Type 'string' is not assignable to type '"CHECKING" | "SAVINGS" | undefined'.

我也用以下方法进行了测试:

export class BankAccount {
  id: number;
  label?: string;
  type: keyof typeof AccountTypes;

  constructor(init?: Partial<BankAccount>) {
    Object.assign(this, init);
  }
}

但是没有用。

typescript
1个回答
0
投票

第一个问题。方法是您要在期望枚举成员的同时尝试传递字符串。

与第二。方法,它只是不起作用,因为在这种情况下,您尝试传递“ CHECKINGS”而不是“ Checking”。

要解决此问题,您可以使用以下选项:

1.使用枚举成员:

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: AccountTypes.CHECKING,
};
const something = new BankAccount(account);

2。像在第二个中一样键入。方法(keyof typeof AccountTypes):

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
};
const something = new BankAccount(account);

3。使用类型别名:

type AccountTypes = 'Checking' | 'Savings';

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
} as const;

// or

const account = {
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking' as AccountTypes,
};

// or

const account: Partial<BankAccount> = { // It would be better to create an interface here
  id: 1,
  label: 'John Doe: Chase Checking ****1892',
  type: 'Checking',
};

const something = new BankAccount(account);

请注意,如果您选择加入enums,最好使用const enum,因为它们可以在生成时完全擦除。

© www.soinside.com 2019 - 2024. All rights reserved.