繁体   English   中英

限制 TypeScript 中函数的返回类型

[英]Restricting Return Type Of Function in TypeScript

假设我有以下课程。

class MyClass {
  firstMethod: (a: string) => string;
  secondMethod: (b: number) => number;
}

我想创建一个函数,它接受这个类作为它的第一个参数。 这应该通知第二个参数的返回类型的类型,一个函数。 不管结构类型如何,我希望将返回类型字段限制为 MyClass 中定义的字段。 例如:

好的:

myFunction(MyClass, () => {
  return {
    firstMethod: (a) => a,
    secondMethod: (b) => b,
  };
});

坏的:

myFunction(MyClass, () => {
  return {
    firstMethod: (a) => a,
    secondMethod: (b) => b,
    thirdMethod: (c: boolean) => c,
  };
});

额外的字段会导致类型错误。 应该改变firstMethodsecondMethod的类型。

现在,我像这样尝试没有成功。

任何帮助将不胜感激。 谢谢!

这是你想要的吗?

const myFunction = (a : MyClass): MyClass => {
  return {
    firstMethod: (a: string) => a,
    secondMethod: (b: number) => b,
  };
}

暂无
暂无

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

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