Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A type literal property cannot have an initializer in TypeScript

This is my class in title gives me an error of

"A type literal property cannot have an initializer"

If I remove title its working fine, I'm using Angular 4.3.1

export class MyClass{
    data:[
      {
        blood:string;
        title:string = 'Blood Pressure - Systolic (mm/Hg)';
      }
    ]
}

Thanks a lot.

like image 788
RajnishCoder Avatar asked Sep 05 '17 07:09

RajnishCoder


3 Answers

In your object you can't specify the type for properties when you also have value for them.

In this case you haven't specified the object, but it's type. I think you can create an interface (shape) for your array's items and use that for strong type.

interface Item {
   blood: string,
   title: string
}

export class MyClass{
    data: Item[] = [];
}

Here your array holds items with the shape Item. And you can push data into it which corresponds to the shape of the items.

data.push({
    blood: 'B (III) Rh (+)',
    title: 'Blood Pressure - Systolic (mm/Hg)'
});
like image 156
Suren Srapyan Avatar answered Nov 17 '22 08:11

Suren Srapyan


Seems like you are trying to make an object directly instead of a class. Or you are trying to make a class in which some variables have default values. A better approach for the same would look like:

export class SomeClass {
param1: string[]; 
param2: string; 

constructor(param1?: string[],
            param2?: string) {

    this.param1 = param1 || [];
    this.param2 = param2 || '';
}
}
like image 37
Sumit Agarwal Avatar answered Nov 17 '22 08:11

Sumit Agarwal


Create a class for the object you are trying to create.

export class MyData {
    blood: string;
    title: string;
}

In your other class, you can now use it.

export class MyClass{
    data: MyData[] = [];
    data.push({
        blood: 'foo',
        title: 'Blood Pressure - Systolic (mm/Hg)'
    });
}
like image 34
JSON Derulo Avatar answered Nov 17 '22 07:11

JSON Derulo