In angular 18 I have usual TypeScript ("module": "ES2022")
I have basic class:
class Item {
id: number = 0;
title: string = '';
active: boolean = false;
date: Date = new Date();
getTitle() {
return this.title;
}
}
And some object (from Json for example):
const someObj = {
id: 1,
title: 'some title',
active: 1 // notice that type here in number, not boolean
}
I want to create new object with class Item,
with all methods available, and with all properties from someObj casted to types from class.
I tried:
const realItem = new Item();
const myItem = <Item> someObj;
const myItem2 = someObj as Item;
const myItem3 = <Item> someObj as Item;
const myItem4 = Object.assign(new Item(), someObj);
console.log(realItem)
console.log(myItem);
console.log(myItem2);
console.log(myItem3);
console.log(myItem4);
None of this ways gives the real Class object, like realItem.
And of course, the method getTitle is not available this way.
The only way I see, to make huge constructor, with checking types:
constructor(res: any = {}) {
Object.keys(res).forEach(key => {
if (this.hasOwnProperty(key)) {
const type = typeof this[key as keyof typeof this];
if (type === 'boolean') {
// @ts-ignore
this[key as keyof typeof this] = !!res[key];
} else if (type === 'number') {
// @ts-ignore
this[key as keyof typeof this] = +res[key];
} else if (type === 'string') {
// @ts-ignore
this[key as keyof typeof this] = String(res[key]);
} else if (type === 'object' && this[key as keyof typeof this] instanceof Date) {
// @ts-ignore
this[key as keyof typeof this] = new Date(res[key]);
} else {
this[key as keyof typeof this] = res[key];
}
}
})
}
But I can't believe , that there is no simple and right way to do this.

activebeing abooleanand not anumber, and TypeScript is gone when that code runs). JS doesn't have a strong enough type system to do this sort of runtime stuff. You have to write it yourself, sorry. See the linked q/a for more info.