typescript枚举默认值

时间:2017-07-28 01:44:04

标签: typescript enums

我刚开始用Aurelia框架学习Typescript。我已经使用ViewEngineHooks http://davismj.me/blog/template-constants/在Aurelia模板中将Matthew Davis的博客TypeScript Enums实现到了Aurelia的Todo应用程序。

我希望将默认枚举值设置为列表中的第二个值,并将默认值设置为列表中的第一个值。

另外,我想请知道{Todo,Priority}或{Todo}是否需要导入,如todo-list.ts所示

todo.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;
    }

待办事项-list.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();
    }
  }

todo.html

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

2 个答案:

答案 0 :(得分:1)

据我所知,在声明变量时,您无法设置枚举的默认值,与数字相同,或者布尔值不是默认值。 但是,您可以像在构造函数(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)时,您不必导入它。

答案 1 :(得分:1)

model.bind s

上使用<option>

没有任何改变的原因是因为没有将“正确”值“分配”给<option>。为此,您需要使用model属性。

<select id="priority" value.bind="type">
  <option model.bind="Priority[type]" repeat.for="type of Priorities">
    ${type}
  </option>
</select>