首页 > 解决方案 > 如何在接口和类中强制自定义声明类型?

问题描述

我创建了我的自定义类型,它实际上是一个命名的原始类型,目的是明确定义那里有什么样的数字或什么样的名字。例如:

export declare type AmountOfCredits = number;
export declare type AmountOfMoney = number;
export declare type AmountOfProduct = number;
export declare type BankAccountNumber = string;
export declare type CompanyName = string;
export declare type CountryName = string;
export declare type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export declare type Days = number;
export declare type ID = number;
export declare type Month = number;
// ...etc

现在我可以使用这个界面了:

export interface EmployeeInterface {
  id: ID;
  user_id: ID;
  mother_name: PersonName;
  place_of_birth: SettlementName;
  date_of_birth: ISODate;
  name: PersonName;
}

但在课堂上,这也很有效:

export class Employee implements EmployeeInterface {
  id: number;
  user_id: number;
  mother_name: string;
  place_of_birth: string;
  date_of_birth: string;
  name: string;
}

我可以以某种方式强制类中只接受自定义声明的类型而不是number原始string类型吗?

标签: typescripttypesinterfacetype-declaration

解决方案


推荐阅读