【问题标题】:Restricting Return Type Of Function in TypeScript在 TypeScript 中限制函数的返回类型
【发布时间】:2020-03-27 03:28:10
【问题描述】:

假设我有以下课程。

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 的类型。

现在,我尝试像this 一样失败。

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

【问题讨论】:

    标签: typescript class generics types restrict


    【解决方案1】:

    这是你想要的吗?

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

    【讨论】:

    • 不,不是。有几个原因: 1. 参数需要是MyClass 的构造函数,而不是实例。 2.myFunction 返回无效。 3. 名单还在继续。您似乎没有真正阅读过上面的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2019-09-03
    相关资源
    最近更新 更多