Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from an object of a type to another object of different type

Tags:

typescript

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.

like image 719
alex Avatar asked Oct 25 '25 12:10

alex


1 Answers

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
console.log(transformed.Age) //99 But also Type Error!!

Note that transformed.Age still contains data, it will just also throw a type error and complain in the IDE.

It will however allow you to pass the object to a parameter requiring type B.

If you were to cast it back to A, you would still be able to access the data in Age.

This is not not very type safe. It would be better to create a method that maps it from one type to another, this way you can ensure 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) //""
like image 54
Alex Avatar answered Oct 27 '25 10:10

Alex