How to reduce javascript object to only contain properties from interface

It is not possible to do this. The reason being interface is a Typescript construct and the transpiled JS code is empty

//this code transpiles to empty!
interface MyInterface {
  test: string;
}

Thus at runtime there is nothing to ‘work with’ – no properties exist to interrogate.

The answer by @jamesmoey explains a workaround to achieve the desired outcome.
A similar solution I use is simply to define the ‘interface’ as a class –

class MyInterface {
  test: string = undefined;
}

Then you can use lodash to pick the properties from the ‘interface’ to inject into you object:

import _ from 'lodash';  //npm i lodash

const before = { test: "hello", newTest: "world"};
let reduced = new MyInterface();
_.assign(reduced , _.pick(before, _.keys(reduced)));
console.log('reduced', reduced)//contains only 'test' property

see JSFiddle

This is a pragmatic solution that has served me well without getting bogged down on semantics about whether it actually is an interface and/or naming conventions (e.g. IMyInterface or MyInterface) and allows you to mock and unit test

Leave a Comment