确保我的函数返回变异对象作为同一个类打字稿的实例?

Mic*_*elB 5 javascript immutability javascript-objects typescript

export const FilterUndefined = <T extends object>(obj: T): T => {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    return value ? { ...acc, [key]: value } : acc;
  }, {}) as T;
};
Run Code Online (Sandbox Code Playgroud)

我正在迁移数据库和清理旧数据结构的一部分,某些键的某些值最终变成了字面意思undefined。键将仍然存在并具有值undefined

我做了这个函数,但是在用它修改了一个类对象之后,它将不再是同一个类的实例。我怎样才能让它返回一个与输入参数属于同一个类的实例的对象?

as T 使 TS 编译器关闭,仅此而已。

我还尝试获取该对象的原型,return new prototype(obj)或者return new prototype.constructor(obj)

原型的控制台日志如下所示:

PROTOTYPE TestClass {}
Run Code Online (Sandbox Code Playgroud)

我正在使用此设置进行测试:

  it('should return the same type that it receives', () => {
    class TestClass {
      name: string;
      optionalProperty?: any;
    }

    let testObject = new TestClass();
    testObject.name = 'My Name';
    testObject.optionalProperty = undefined;

    console.log(testObject instanceof TestClass);
    testObject = FilterUndefined(testObject);

    console.log(testObject instanceof TestClass);
    console.log(testObject);

    expect(testObject).instanceOf(TestClass);
  });
Run Code Online (Sandbox Code Playgroud)

编辑:JSFiddle:https ://jsfiddle.net/3sdg98xt/2/ 但从vscode复制粘贴没有任何问题运行它我收到一个错误'execpted 表达式,得到';'

car*_*vin 1

该解决方案将通过删除具有未定义值的键来改变输入对象。

function removeUndefined <T>(object: T): T {
    for (const id in object) {
       if (object[id] === undefined) {
          delete object[id];
       }
    }
    return object;
}
Run Code Online (Sandbox Code Playgroud)

看来它适用于您的测试用例:Test in typescript Playground