[SOLVED] Convert from an object of a type to another object of different type

Issue

What is the smartest way to convert:

export interface A {
    Id: number;
    Name: string;
    Surname: string;
    Age: number;
}

export interface B {  //<---EDITED (at first i wrote "A"- sorry guys
    Id: number;
    Name: string;
    Surname: string;
    City: string;
}


let source :A = {
    Id = 1
    Name = "aaaa"
    Suramne = "bbbb"
    Age = 99
}

to:

{
    Id = 1
    Name = "aaaa"
    Suramne = "bbbb"
    City = ""
}

a sort of downcast, mapping only the existing properties (with the same name) and lost the others are missing in the target object.

Solution

interface A {
    Id: number;
    Name: string;
    Surname: string;
    Age: number;
}

interface B {
    Id: number;
    Name: string;
    Surname: string;
    City: string;
}


let source : A = {
    Id: 1,
    Name: "aaaa",
    Surname: "bbbb",
    Age: 99
}

let transformed = source as unknown as B;
console.log(transformed.Id) //1
console.log(transformed.Name) //"aaaa"
console.log(transformed.Surname) //"bbbb"
console.log(transformed.City) //undefined

This is not in any way type safe though, It may be better to create a method that maps it from one type to another, this way you can insure type safety the entire time

let TransformAToB = (input: A): B => {
    return {
        Id: input.Id,
        Name: input.Name,
        Surname: input.Surname,
        City: ""
    }
}

let transformed2 = TransformAToB(source)
console.log(transformed.Id) //1
console.log(transformed.Name) //"aaaa"
console.log(transformed.Surname) //"bbbb"
console.log(transformed.City) //""

Answered By – StiyAle

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *