【问题标题】:Typescript - how to declare an attribute name started with @?Typescript - 如何声明以@开头的属性名称?
【发布时间】:2018-06-25 19:50:34
【问题描述】:

我正在尝试使用名为“@type”的属性在 TypeScript 中声明一个类型,以便与我的 Java API 中的某些类型相对应:

export interface Foo {
    id : string;
    name : string;
    @type: string;
}

但是,我的 VS Code 中出现编译器错误。

为了确保这不是 JavaScript 问题,我在浏览器控制台中尝试了let test = JSON.parse('{"@type" : "value"}'),它工作正常。

那么我该如何声明这样一个属性名以@开头的类型呢?

【问题讨论】:

  • 用引号括起来?例如:{"@type": string}

标签: javascript json typescript


【解决方案1】:

Javascript(和Typescript)有相对宽松的member命名规则;这意味着您可以使用不常见的字符甚至空格。但为了做到这一点,您需要将它们封装在quotes 中:

interface MyInterface {
    property1: string;
    "@property 2": string;
}

const myobj: MyInterface = {
    property1: "Value 1",
    "@property 2": "Value 2"
}

如果您确实使用非字母数字属性名称,则必须使用 index 语法来访问它们:

console.log(myobj.property1); // Dot notation
console.log(myobj["@property 2"]); // Index notation

有关更多有趣和深入的信息,请查看 Mathias Bynens' 博客条目:

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 2017-02-08
    • 1970-01-01
    • 2021-12-06
    • 2018-07-04
    • 2017-04-04
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多