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 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) //""