首页 > 解决方案 > 在跳过字段的同时构造一个对象

问题描述

打字稿新手。我正在尝试用任意形状的另一个对象构造一个对象:

  class Thing {
    a?: string;
    b?: string;
  }
  const input = {a: 'a', b: 'b', c: 'c'}
  const builtInput: Thing = {
    ...input
  }
  console.log(builtInput)

我期待

{a: "a", b: "b"}

但得到

{a: "a", b: "b", c: "c"}

我也尝试过thing作为类型和接口。没有任何效果。我是否期待太多魔法并需要编写自定义构造函数?有打字稿的方法吗?

标签: typescript

解决方案


您应该编写一个函数,该函数将创建一个带有所需键的对象。我认为,这样的事情会很有用:

// initial type
type Input = {
  a: string;
  b: string;
  c: string;
}

// result type
type Build = Pick<Input, 'a' | 'b'>;

const getFilteredInput = <T extends {}, K extends keyof T>(obj: T, requiredVals: Array<K>) => {
  return requiredVals.reduce((acc, current) => {
    if (current in obj) {
      acc[current] = obj[current];
    }

    return acc;
  }, {} as Pick<T, K>);
  // Pick describes an object from T with only K keys
};

const input: Input = {
  a: 'a',
  b: 'b',
  c: 'c',
};

const build: Build = getFilteredInput(input, ['a', 'b']);

console.log('build', build);

推荐阅读