定义作为另一个子集的对象类型

时间:2019-04-22 10:48:26

标签: typescript types

我在键入通用函数时遇到困难。该函数被赋予一个对象,并返回一个包含给定对象属性的对象。因此,是Partial,但是属性在编译时是已知的。这是我到目前为止的所有信息(不起作用)。

type FromFunction = <Input, Keys extends keyof Input>(
  input: Input,
  keys: Array<Keys>
) => {
  [property in Keys]: Input[Keys];
};



export const from: FromFunction = <Input>(input, ...keys) => {
  return keys.map(key => input[key]);
}

但是当我尝试使用它时,出现此错误:

// use, which should return { text: 'string' }.
from({ text: 'string', other: 1 }, 'text');

// error
Argument of type '"text"' is not assignable to parameter of type '"text"[]'.ts(2345)

有没有办法做到这一点?我不想使用anyPartial<Input>,因为返回对象是在编译时确定的。

1 个答案:

答案 0 :(得分:1)

如果键在编译类型时是已知的,则您可能要使用Pick,它允许您从类型中选择一些属性:

type FromFunction = <Input, Keys extends keyof Input>(
    input: Input,
    ...keys: Array<Keys>
) => Pick<Input, Keys>



export const from: FromFunction = <Input, Keys extends keyof Input>(input: Input, ...keys: Keys[]) => {
    // changed the implementation, I think you want to return an object not an array.
    //We can also do tuples (ie arrays) if you want but that is a bit different, let me know if that is what you need.
    var result = {} as Pick<Input, Keys>
    for (let k in keys) {
        result[k] = input[k]
    }
    return result;
}

// use, which should return { text: 'string' }.
from({ text: 'string', other: 1 }, 'text');