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.
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) //""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With