简体   繁体   English

TypeScript-推断或声明Pick类型作为函数的返回值

[英]TypeScript - inferring or declaring Pick type as a functions return value

Considering the following simplified function, which accepts an object and a property of that object, and returns a clone of that object with only the specified property: 考虑以下简化的函数,该函数接受一个对象和该对象的属性,并返回仅具有指定属性的该对象的克隆:

export function clonePick<T, K extends keyof T>(obj: T, prop: K) {
  const keys = Object.keys(obj).filter(k => k === prop)
  return keys.reduce(
    (clone: any, key: string) => {
      return { ...clone, [key]: obj[key as keyof T] };
    },
    {}
  );
}

This is essentially identical behavior to Pick except for a value instead of a type, and so it's return type could be expressed as: 除了值而不是类型外,这与Pick基本上是相同的行为,因此它的返回类型可以表示为:

Pick<T, prop>

Except the above is not valid typescript. 除上述无效的打字稿外。 However, we can know the value of prop well before runtime when calling the function: 然而,我们可以知道调用函数时运行前支撑良好的价值:

interface ITest {
  numProp: number;
  strProp: string;
}

const test = { numProp: 1, strProp: '1' }; // <-- type is ITest

const testClone = clonePick(test, 'numProp') // <-- type is any

I can easily declare this explicitly: 我可以轻松地明确声明这一点:

const testClone: Pick<ITest, 'numProp'> = clonePick(test, 'numProp')

But it would be a lot more maintainable if I could include that behavior as part of the above function. 但是,如果我可以将该行为作为上述功能的一部分包含在内,那么它将更具可维护性。 Is this possible? 这可能吗? Preferably it can work with an array of properties as well as a single prop 优选地,它可以使用一系列属性以及单个道具

You won't get the compiler to infer that complicated reduce call to a Pick , it won't even și it for simpler things such as { [prop]: obj[prop] } . 您不会让编译器推断出对Pick复杂的reduce调用,对于{ [prop]: obj[prop] }之类的更简单的事情,它甚至也不会。 Your best option is to use an annotation for the return type of the function. 最好的选择是对函数的返回类型使用注释。

export function clonePick<T, K extends keyof T>(obj: T, prop: K): Pick<T,K> {

  return { [prop]: obj[prop] } as any;
}


interface ITest {
  numProp: number;
  strProp: string;
}

const test = { numProp: 1, strProp: '1' }; // <-- type is ITest

const testClone = clonePick(test, 'numProp') // 

testClone.numProp
testClone.strProp // err

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM