Angular 8+TypeScript3.4.5接口含短划线属性报错,后端JSON短划线属性如何处理?
Hey there, let's break down what's happening here and how to fix it!
First, the errors you're seeing stem from a TypeScript syntax rule: identifiers (like property names) can't include hyphens. When you write created-date, the compiler misinterprets it as created minus date—that's why you get TS1128 and TS1005 errors.
Now let's cover two solid solutions that fix the syntax issue and handle mapping the backend's hyphenated JSON properties to your frontend code:
Solution 1: Fix the Interface Directly (Simplest Approach)
The easiest fix is to wrap hyphenated property names in double quotes to treat them as string literals. This makes TypeScript happy, and Angular's HttpClient will automatically map the backend's JSON fields to these interface properties.
Here's your corrected interface:
export interface Test { id: string; "created-date": number; "import-by": string; }
When accessing these properties, use bracket notation (dot notation won't work with hyphens):
this.http.get<Test>('/your-api-endpoint').subscribe(test => { console.log(test["created-date"]); // Works perfectly });
Solution 2: Use CamelCase in Frontend (Idiomatic TypeScript)
If you prefer using camelCase property names (the standard in TypeScript), switch from an interface to a class and use property mapping with class-transformer (a lightweight library).
Steps to implement:
- Install a compatible version (match your TypeScript 3.4.5 setup with v0.2.x):
npm install class-transformer@0.2.3 --save - Create a class with
@JsonPropertydecorators to link backend hyphenated fields to frontend camelCase properties:import { JsonProperty } from 'class-transformer'; export class Test { id: string; @JsonProperty("created-date") createdDate: number; @JsonProperty("import-by") importBy: string; } - Convert the raw JSON response to a class instance when fetching data:
import { plainToClass } from 'class-transformer'; import { map } from 'rxjs/operators'; this.http.get('/your-api-endpoint').pipe( map(rawData => plainToClass(Test, rawData)) ).subscribe(test => { console.log(test.createdDate); // Use dot notation with camelCase! });
Bonus: Manual Mapping (No Third-Party Library)
If you don't want to add a dependency, manually map the raw JSON to a camelCase object:
// Define a camelCase interface export interface Test { id: string; createdDate: number; importBy: string; } // When fetching data: this.http.get<any>('/your-api-endpoint').subscribe(rawData => { const test: Test = { id: rawData.id, createdDate: rawData["created-date"], importBy: rawData["import-by"] }; // Use the camelCase test object here });
Pick the solution that fits your workflow best—all of them will resolve the syntax errors and correctly map the backend's JSON data!
内容的提问来源于stack exchange,提问作者mitha.s

