Hi i am trying to get ID card details in a component and form an object "idCardDetails".
In JS i was able to dynamicaly add key and values :
let myObj = {}; myObj.name = "sid"; myObj.num= 4444;
I cant create such a dynamic obj in Type script.
I tried this in TS angular
IdCardDetails: {name: string, empcode: number, bloodgroup: string}; IdCardDetails.name = this.idName; // error cannot set property for undefined
Is this a error occurring with rules of Typescript or Angular?
what will be solution to dynamicaly create an object?
Is it necessary always go with class based object creation in angular?
CodePudding user response:
If you don't know all keys in advance then you can use TypeScript's Record
utility in the following fashion where Keys
are the object types and Type
is the type you want the object should have
Record<Keys, Type>
So, you'd write your code as below,
const idCardDetails: Record<string, number | string> = {};
idCardDetails.name = 'John';
idCardDetails.id = 10;
You can read more about Record utility
CodePudding user response:
You have couple of options for the task you want.
first if you know the fields create an interface
export interface ITest {
name:string, // this will make sure ITest must have name in string type.
age?:number, // this will allow you not to enter age (can be undefined)
[key:string]: any, // will allow you to put what ever key you would like (is more powerful but typescript will not always complete example below,
}
// notice I can avoid using age.
const test:ITest = {
name:'test' // I must provide some initial string
}
test.value = true; // will be accepted because of [key:string]