Reputation: 1371
I'm trying to declare a type in TypeScript with an attribute named "@type" in order to correspond with some type from my Java API:
export interface Foo {
id : string;
name : string;
@type: string;
}
However, I'm getting a compiler error in my VS Code.
Just to make sure it's not a JavaScript issue, I tried let test = JSON.parse('{"@type" : "value"}')
in the browser console and it works fine.
So how can I declare such a type with an attribute name started with @?
Upvotes: 3
Views: 1832
Reputation: 10682
Javascript (and Typescript) have relatively liberal member
naming rules; meaning that you can use uncommon characters and even space. But in order to do so, you need to encase them in quote
s:
interface MyInterface {
property1: string;
"@property 2": string;
}
const myobj: MyInterface = {
property1: "Value 1",
"@property 2": "Value 2"
}
If you do use non-alphanumeric property names, you'd have to use the index
syntax to access them:
console.log(myobj.property1); // Dot notation
console.log(myobj["@property 2"]); // Index notation
For more interesting and in-depth information, review Mathias Bynens' blog entries:
Upvotes: 7