创建一个包含 class 的所有静态属性的映射类型

Create a mapped type containing all the static properties of a class

给定 类:

class EnumerationDTO {
  designation: string;
  id: number;
}

class ExecutionStatusDTO extends EnumerationDTO {
    static readonly open: ExecutionStatusDTO = { id: 0, designation: 'Open' };
    static readonly working: ExecutionStatusDTO = { id: 1, designation: 'Working' };
    static readonly waiting: ExecutionStatusDTO = { id: 2, designation: 'Waiting' };
    static readonly resting: ExecutionStatusDTO = { id: 3, designation: 'Resting' };
    static readonly escalated: ExecutionStatusDTO = { id: 4, designation: 'Escalated' };
    static readonly done: ExecutionStatusDTO = { id: 5, designation: 'Done' };
    static readonly removed: ExecutionStatusDTO = { id: 6, designation: 'Removed' };
}

我需要计算 ExecutionStatusDTO 的每个实例在数组中出现的次数,并将该计数保存在类型的对象中:

type statusesCount: {
    done: number;
    escalated: number;
    open: number;
    removed: number;
    resting: number;
    waiting: number;
    working: number;
}

但是statusesCount不能简单定义而是映射自ExecutionStatsDTO

解决方案一:

type statusesCount = Partial<
  {
    -readonly [key in keyof typeof ExecutionStatusDTO]: number;
  }
>;

会给

type statusesCount = {
    prototype?: number;
    done?: number;
    escalated?: number;
    open?: number;
    removed?: number;
    resting?: number;
    waiting?: number;
    working?: number;
}

方案二(使用strictNullChecks更方便):

type statusesCount = {
    -readonly [key in keyof Omit<typeof ExecutionStatusDTO, keyof typeof Function>]: number;
};

会给

type statusesCount = {
    open: number;
    working: number;
    waiting: number;
    resting: number;
    escalated: number;
    done: number;
    removed: number;
}