2

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';
...
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I can do that! Ok, I thought since the properties in JSON were strings I thought the constructor parameters had to be identical. I'll make adjustments and test shortly but I see the errors going away with the few I've moved around. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.