3

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?

Mohamed Ibrahim Elsayed
  • 2,734
  • 3
  • 23
  • 43
  • Does this answer your question? [Is it possible to restrict typescript object to contain only properties defined by its class?](https://stackoverflow.com/questions/49580725/is-it-possible-to-restrict-typescript-object-to-contain-only-properties-defined) – Nishant Jan 20 '21 at 13:37
  • Thanks for guiding me to this question and its answer. It is somewhat similar to mine, but the asker was using classes not interfaces, and the answer is applying it as function parameter and not using assignment as I'm trying to do. – Mohamed Ibrahim Elsayed Jan 21 '21 at 14:40

1 Answers1

1

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.

Rubydesic
  • 3,386
  • 12
  • 27