我刚刚开始学习Typescript的AuriLa框架。我已经用aurelia的todo应用程序的viewenginehookshttp://davismj.me/blog/template-constants/在aurelia模板中实现了matthew davis的blog typescript枚举。
请将默认枚举值设置为列表中的第二个值,并将默认值设置为列表中的第一个值。
另外,我想知道{todo,priority}或只是{todo}是否需要导入,如todo-list所示。ts
待办事项

// Pro Tip: By starting our enum at 1, we ensure that all values in the enum are truthy.
export enum Priority {
    High = 1,
    Medium,
    Low
}

export class Todo {
    @observable done;
    //*** Setting priority: Priority = 2 OR priority: Priority = Priority.Medium - Does not change the default from High / 1 ***
    //constructor(public list: TodoList, public description: string, public priority: Priority = 2, public editing: boolean = false) {
    constructor(public list: TodoList, public description: string, public priority: Priority = Priority.Medium, public editing: boolean = false) {
        this.list = list;
        this.description = description;
        //*** Setting this.priority = 2 OR this.priority = Priority.Medium - Does not change the default from High / 1 ;
        //this.priority = 2;
        this.priority = Priority.Medium;
        this.editing = false;
    }

待办事项列表.ts
//*** Is {Todo} OR {Todo, Priority} needed for importing? ***
//import {Todo} from './todo';
import {Todo, Priority} from './todo';
...
  add(description) {
    if (description) {
      //*** Setting (this, description, 2) OR (this, description, Priority.Medium) - Does not change the default from High / 1 ***
      //this.todos.push(new Todo(this, description, 2));
      this.todos.push(new Todo(this, description, Priority.Medium));
      this.invalidateView();
    }
  }

待办事项.html
<select id="priority" value.bind="type">
  <option value.bind="Priority[type]" repeat.for="type of Prioritys">${type}</option>
</select>

最佳答案

据我所知,当声明变量时,不能设置枚举的默认值,与数字或布尔值相同的方法没有默认值。
但是,您可以为函数参数定义默认值,就像在构造函数(priority: Priority = Priority.Medium)中所做的那样,这样在调用构造函数时不必提供那个参数。
另外两条注释:
不是应该是this.priority = priority; this.editing = editing;而不是this.priority = Priority.Medium; this.editing = false;吗?第二,如果在参数前面放置public,类属性将自动添加并被赋值,因此不需要构造函数的附加行。但是对于更复杂的类,我可能会手动创建和分配属性。
关于您的第二个问题:您需要在引用该枚举时立即导入Priority,例如在编写Priority.Medium时。例如,在不使用枚举名称(例如Priority)比较this.todos[0].priority === this.todos[1].priority类型的两个不同属性时,不必导入它。

关于typescript - typescript 枚举默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45363572/

10-11 23:49