Aurelia ValidationRules.ensure使用TypeScript

时间:2019-02-13 20:03:26

标签: typescript aurelia aurelia-validation

我有一个用ES6和Babel创建的Aurelia项目,我正在尝试将其转换为TypeScript。

在一个代码区域中,我有这样的东西:

tenant.js

import {ValidationRules} from 'aurelia-validation'
export class Tenant{
    constructor(tenantObject){
        Object.assign(this, tenantObject);
    }
} 

ValidationRules
  .ensure(o => o.name).displayName("Tenant Name").required()
  ...
  .on(Tenant);

system.js(VM)

import {ValidationController} from 'aurelia-validation'
import {NewInstance} from 'aurelia-framework'
import {Tenant} from '../models/tenant'
import {BootstrapValidationRenderer} from 'elements/bootstrap-validation-renderer'

export class System{
    static inject = [DataService, NewInstance.of(ValidationController)]
    constructor(dataService, validationController){
       this.dataService = dataService
       this.validationController = validationController

       this.validationController.addRenderer(new BootstrapValidationRenderer())
    }

    async activate() {
       let data = await this.dataService.getTenant(1);
       this.tenant = new Tenant(data);
    }

    ...
}

system.html

...
<div class="form-group name" >
   <label for="pName" class="form-control-sm">Tenant Name</label>
   <input id="pName" type="text" autofocus class="form-control form-control-sm" value.bind="tenant.name & validate" />
</div>

但是,我现在在tenant.ts中收到一个错误,指出该property 'name' does not exist on type {}

我尝试向name添加一个Tenant属性,但这似乎无济于事。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

aurelia-validation does not似乎在打字。因此,您必须声明以下类型:

ValidationRules
  .ensure((o: Tenant) => o.name).displayName("Tenant Name").required()
  ...
  .on(Tenant);

但是在此之前,您应该将name属性添加到Tenant类中:

export class Tenant{
    public name: string = ''

    constructor(tenantObject){
        Object.assign(this, tenantObject);
    }
} 

P.S。即使aurelia-validation进行过打字,您仍然必须断言type,因为它在方法链的最后接受类名。