首页 > 解决方案 > Angular/Typescript 接口和实现类:带有 `@, $` 字符的属性

问题描述

我在我的 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
}

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

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

标签: javascriptangulartypescripttypescript-class

解决方案


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

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..

推荐阅读