dictatorpants
dictatorpants

Reputation: 21

'Identifier expected' errors and 'not assignable to type number' errors while creating TypeScript class

Still a bit new to coding. I'm trying to create a TypeScript class in an Angular project based on a larger JSON file. I'm not sure if it doesn't like the way the properties were with the string literals, but that was how they were declared in the JSON and I'm not sure if there's a better way to declare them in TS. When I declare the properties, they're fine...

// this all seems ok
export class State {
    'FIPS Code': number;
    'Postal': string;
    'Area Name': string;
    'Less than a high school diploma, 1970': number;
... 
}

When I make a constructor, I get various errors...

// all parameter identifiers say 'identifier expected'
constructor('FIPS Code': number, 'Postal': string,
        'Area Name': string,
        'Less than a high school diploma, 1970': number,
        'High school diploma only, 1970': number,
...) {

    // Type '"FIPS Code"' is not assignable to type 'number'
    this['FIPS Code'] = 'FIPS Code';

    // the next two are ok, I assume because they're strings
    this['Postal'] = 'Postal';
    this['Area Name'] = 'Area Name';

    // everything else remaining says not assignable to type 'number'
    this['Less than a high school diploma, 1970'] = 'Less than a high school diploma, 1970';
...
}

Upvotes: 2

Views: 578

Answers (1)

satanTime
satanTime

Reputation: 13539

please don't mix variables, keys and strings.

you can use a string as a key to access data inside of this or an object. But variables (args of the constructor) should follow rules of their naming.

// all parameter identifiers say 'identifier expected'
constructor(FIPSCode: number, Postal: string,
        AreaName: string,
        Lessthanahighschooldiploma1970: number,
        Highschooldiplomaonly1970: number,
...) {

    // Type '"FIPS Code"' is not assignable to type 'number'
    this['FIPS Code'] = FIPSCode;

    // the next two are ok, I assume because they're strings
    this['Postal'] = Postal;
    this['Area Name'] = AreaName;

    // everything else remaining says not assignable to type 'number'
    this['Less than a high school diploma, 1970'] = Lessthanahighschooldiploma1970;
...
}

Here you can find more info how to declare a variable: https://www.typescriptlang.org/docs/handbook/variable-declarations.html

Upvotes: 1

Related Questions