首页 > 解决方案 > 根据同一类的另一个成员设置 Typescript 类成员的值

问题描述

假设我有一堂课User

export class User {
  constructor(
    userID?: number,
    state?: 'In' | 'Out' | 'Break' | 'Lunch', // for example, but there are more...
    stateVal?: 1 | 2 | 3 | 4,
  ) {}
}

的目的stateVal是使排序按state特定顺序而不是字母顺序,即默认情况下它按字母顺序排序,这可能导致不希望的顺序->

(default, alphabetical)
(1) Break
(2) In
(3) Lunch
(4) Out

(desired order)
(1) In
(2) Break
(3) Lunch
(4) Out

这样,如果我排序 thisstateVal而不是state,我可以得到我想要的顺序。

总的来说,发生的事情是,我从 RESTful API 获取用户列表,然后我必须stateVal通过循环每个用户并stateVal手动添加来添加(因为stateVal服务器不提供)。

但是这可以在课堂上完成吗?

我在想:

是否可以自动将state属性stateVal取决于自身的值?

IE

如果state是“在”,自动设置stateVal为 1——从类的角度来看?以某种方式强制执行此逻辑?

标签: javascripttypescriptclass

解决方案


推荐阅读