【问题标题】:Angular 2 - Typescript choking on object dot notation, expects ';'Angular 2 - 打字稿在对象点符号上窒息,需要';'
【发布时间】:2016-04-10 18:36:58
【问题描述】:

我是 TypeScript 和 Angular 2 的新手。我正在将一个项目从 Angular 1 转移过来,但我无法将我的一些属性定义放入 Angular 2 组件中。

我有这些属性定义:

import { Component } from 'angular2/core';
@Component({
  selector: 'contact-detail',
  templateUrl: 'app/contacts/contact-detail.template.html',
  styleUrls: ['app/contacts/contact-detail.style.css']
})
export class ContactDetailComponent {
  contactFormOptions = {};
  contactFormOptions.initDateDefault = '';
  contactFormOptions.followUpDateDefault = '';
  contactBasicInfo: {};
  contactBasicInfo.bdMonth = '0';
  contactBasicInfo.bdDay = '0';
}

Angular 1 很适合我用这种方式定义对象属性(如 contactFormOptions.initDateDefault = '';)。使用点语法。然而,Typescript 对这些属性的点表示法感到窒息,并说; 是预期的。为什么?我错过了什么?

谢谢!

【问题讨论】:

  • 我猜这些属性没有定义。您应该使用括号表示法
  • 对此也感到窒息:contactFormOptions['initDateDefault'] = moment(); 说它期望=。我正在尝试在这些行中定义属性以供以后使用。
  • 您能否提供更多有关此代码运行位置的上下文? :)
  • 好的,我添加了整个组件。不过,我确实删除了与定义这些属性无关的方法和东西。

标签: angularjs typescript javascript-objects


【解决方案1】:

要让 TypeScript 理解 moment.js,您需要一个定义文件。幸运的是,moment.js 提供了一个,您只需要添加参考,这也已在此处找到,在 Defintely Typed:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/moment/moment.d.ts

为了清楚起见,需要在代码中添加的是:

declare var moment: moment.MomentStatic;

【讨论】:

  • 我认为这与时刻无关。即使我只是试图将值设置为空字符串(根本不使用时刻),它也会做同样的事情。
  • 更新了我的问题以从等式中删除 moment.js。它仍然在对象属性的点符号上窒息。
【解决方案2】:

好的,我只是刚接触 OOP 世界。我需要做的是声明属性及其类型,然后在构造函数(或方法)中赋值。

export class ContactDetailComponent {
  contactFormOptions: any = {};
  contactBasicInfo: any = {};

  constructor ( ) {
    this.contactFormOptions.initDateDefault = moment();
    this.contactFormOptions.followUpDateDefault = moment().add(7, 'days');
    this.contactBasicInfo.bdMonth = '0';
    this.contactBasicInfo.bdDay = '0';
  }
}

【讨论】:

    猜你喜欢
    • 2016-11-05
    • 2023-03-28
    • 2018-05-10
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多