我如何在Typescript中为对象分配一个空对象?

时间:2015-10-16 06:30:06

标签: javascript angularjs typescript

我有这样的代码:

界面:

interface IAuthService {

    forms: {
        chn: any;
        che: any;
        cpw: any;
        fpw: any;
        login: any;
        logout: any;
        r: any;
        rpw: any;
    };

我的课程:

class AuthService implements IAuthService {

    forms: {
        chn: any;
        che: any;
    };

static $inject = [
    '$interval'
];

constructor(
    public $interval
    ) {

    this.forms = {
        chn: {},
        che: {}
    };

}

有人可以告诉我是否可以进行分配:

  chn: {},
  che: {}

在代码的前几行中,如果有什么理由在构造函数中执行它?如果可以在

内进行
  forms: {
        chn: any;
        che: any;
那我怎么能这样做?我尝试了一些不同的组合,但都给了我语法错误。

  forms: {
        chn: any = {};

给了我错误:

  

严重级代码描述项目文件行错误TS2420类   ' AuthService'错误地实现了界面' IAuthService'。类型   财产的形式'是不相容的。       输入' {chn:any; }'不能分配给' {chn:any; che:any;}'。         物业' che'缺少类型' {chn:any; }&#39 ;.用户C:\ H \ user \ user \ app \ services \ authservice.ts 1

1 个答案:

答案 0 :(得分:0)

您可以使用“?”将某些字段(属性)标记为可选:

interface IAuthService {

forms: {
    chn: any;
    che: any;
    cpw?: any;
    fpw?: any;
    login?: any;
    logout?: any;
    r?: any;
    rpw?: any;
};

在这种情况下,你可以做出这样的任务:

this.forms = {
    chn: {},
    che: {}
};

和此:

this.forms = {
    chn: {},
    che: {},
    cpw: {}
};

但不是这样:

this.forms = {
    chn: {}
};
相关问题