Quantcast
Channel: how to dynamically add value to object in an array of objects in TypeScript? - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by shuk for how to dynamically add value to object in an array of objects in TypeScript?

$
0
0

as you made the class for the purpose of typechecking - I'm guessing you mixed up javascript's class and typescript's interface:

an interface is only present during development, and gone in your actual production app.a class is a living js object that is compiled into a functioning object in your app.

an interface for typechecking may look like this:

interface Name {  name: string;  age: number;  getConcat: () => string; // hints about the presence of a function that returns a string, within the typed object - but is not a function by itself!}

while a class requires a bit modification

export class Names {    name: string;    age: number;    constructor(name: string, age: number) { // pass arguments to initialize the class object      this.name = name;      this.age = age;    }    getConcat() {        return this.name +''+ this.age;    }}

using interfaces, you could say that the array of names you have is of type Name[], meaning:

function getConcat () {   return this.name +''+ this.age}const names: Name[] = [{name: 'a', age: 1, getConcat: getConcat }, {name: 'b', age: 2, getConcat: getConcat },...];

and throughout your code development, you will be hinted about the already preset getConcat method, and be warned if it is not there now, or in future.

But in order to use the class for both typechecking AND the getConcat function, you will have to map each object into a class:

const objects = [{name: 'a', age: 1}, {name: 'b', age: 2}];const names: Name[] = objects.map(obj => new Name(obj.name, obj.age));

And now you can access any method you declared within Name class, for each item in names array.

You can actually mix the two up, initializing the js classes as shown above, while typechecking the class itself:

export class Name implements NameInterface {    name: string;    age: number;    constructor(name: string, age: number) {       this.name = name;      this.age = age;    }    getConcat() {        return this.name +''+ this.age;    }}

And now you will be warned if your class object has not implemented any member of the NameInterface declared members (say you forgot to add the getConcat function within the class).


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>