A type literal property cannot have an initializer in TypeScript
Solution 1
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)'
});
Solution 2
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 || '';
}
}
Solution 3
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)'
});
}
Related videos on Youtube
RajnishCoder
Hi, I'm a creator of bugs but, they call them features :D, [ "I asks stupid questions", "I break things", "I make new things", "I learn things" ]
Updated on July 23, 2022Comments
-
RajnishCoder almost 2 years
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 usingAngular 4.3.1
export class MyClass{ data:[ { blood:string; title:string = 'Blood Pressure - Systolic (mm/Hg)'; } ] }
Thanks a lot.