How to reduce javascript object to only contain properties from interface

后端 未结 7 1380
迷失自我
迷失自我 2020-12-06 04:29

When using typescript a declared interface could look like this:

interface MyInterface {
  test: string;
}

And an implementation with extra

相关标签:
7条回答
  • 2020-12-06 04:58

    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

    0 讨论(0)
提交回复
热议问题