跳过字段时构造对象

时间:2020-09-23 12:39:02

标签: typescript

打字稿的新功能。我试图用任意形状的另一个对象构造一个对象:

  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用作类型和接口。没事。我是否期望太多魔术,并且需要编写自定义构造函数?有打字稿的方式吗?

1 个答案:

答案 0 :(得分:0)

您应该编写一个函数,该函数将创建具有所需键的对象。我认为,类似这样的方法会很有用:

// 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);
相关问题