【问题标题】:Angular/Typescript interface and implementing class: Attributes with `@, $` characters in themAngular/Typescript 接口和实现类:带有 `@, $` 字符的属性
【发布时间】:2020-11-20 06:49:48
【问题描述】:

我在我的 Angular 应用程序中遵循 JHipster 的方法,我相信它几乎是基于最佳实践的。就模型而言,这就是他们的做法:

export interface IPerson {
  id: number;
  firstName: string;
  lastName: string;
}

export class Person implements IPerson {

  constructor(
    public id: number,
    public firstName: string,
    public lastName: string) {}

}

我在尝试添加以下属性时遇到了问题(由我正在使用的第三方 API 决定,还有许多其他包含其他特殊字符,例如 $ 等):

export interface IPerson {
  ...
  '@type': string; // here it's ok
}

export class Person implements IPerson {

  constructor(
    ...
    // here, however, the compiler goes 
    // nuts, showing it in red and underlined
    public '@type': string
}

所以,问题似乎不是类本身的用法,而是构造函数中的用法,以这种方式声明。

有没有人知道如何至少解决这个问题?

【问题讨论】:

  • 为什么在构造函数中使用public '@type': string
  • 因为我认为我应该在构造函数中初始化它,就像接口中的其他属性一样。还有其他方法吗?
  • 您也可以在构造函数之外将其初始化为类变量。

标签: javascript angular typescript typescript-class


【解决方案1】:

我不知道为什么这是“最佳实践”,但是如果您想在构造函数中分配所有属性,那么您只需为构造函数参数选择另一个名称。

class Person implements IPerson {
    '@type': string;
    constructor(type: string, public name: string) {
        this['@type'] = type;
    }
}

但是,如果Person 没有附加任何行为,我认为创建一个类根本没有多大价值。我会做的

const person: IPerson = { '@type': 'some_type', name: 'developer10' };

我什至会说具有长参数列表的构造函数是“不好的做法”...

const person = new Person('this', 'that', 'first', 'last); // is that the correct order i dunno..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-25
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2015-12-20
    • 2017-07-16
    相关资源
    最近更新 更多