对类中的成员使用枚举

时间:2020-05-13 22:48:03

标签: typescript

我有以下定义:

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

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

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

...当我尝试做类似的事情时:

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

我收到以下错误:

属性“类型”的类型不兼容。 类型'string'不能分配给类型'“ CHECKING” | “节省” |未定义”。

我也做了一些测试:

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

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

...但是没有用。

注释:

这种情况很特殊,这不像我没有使用枚举定义,基本上我的问题是我定义了一个js文件,并在模拟测试中使用了一些定义,所以基本上普通对象,例如如果我们从服务器获取它,那么我尝试在测试中定义该普通对象,然后出现错误。

1 个答案:

答案 0 :(得分: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,因为它们可以在构建世代中完全擦除。

相关问题