Reputation: 2964
I'm a beginner to Typescript, and I have a case in which I'm assigning an object to another object that follows an interface that I've defined. The problem is that the receiving object takes all the properties of the source object, even those that are not defined in the interface, which later causes problem on calling an API. I've simplified it with the following example:
interface MyInterface {
x: string;
y: number;
}
const sourceObject = {x: 'name', y: 35, z: false};
const receivingObject: MyInterface = sourceObject;
console.log(receivingObject); // {x: "name", y: 35, z: false}
I've also tried to use casting as follows:
const receivingObject: MyInterface = sourceObject as MyInterface;
I then had to solve by removing the unneeded properties from the source object, but I was wondering if there is an elegant way to achieve this in Typescript?
Upvotes: 5
Views: 1746
Reputation: 3476
You can use io-ts Exact Types.
import * as t from 'io-ts'
import { getOrElseW } from "fp-ts/Either";
const MyInterface = t.type({
x: t.string,
y: t.number
})
type MyInterfaceType = t.TypeOf<typeof MyInterface>
const sourceObject = {x: 'name', y: 35, z: false};
const getOrNull = getOrElseW(() => null)
const receivingObject: MyInterfaceType | null =
getOrNull(t.exact(MyInterface).decode(sourceObject));
console.log(receivingObject) // { x: 'name', y: 35 }
You cannot do this without a library or additional javascript code as typescript types are stripped at runtime.
Upvotes: 1