【问题标题】:Why my class method is not able to get the params types from its interface?为什么我的类方法无法从其接口获取参数类型?
【发布时间】:2021-11-09 21:12:35
【问题描述】:

我在下面写了这段代码来显示我的问题

type MyFunction<T> = (req: string, res: number) => T;

interface ITest {
  store: MyFunction<void>;
}

class Test implements ITest {
  store(req, res) { //req, res got implicit any type
      req.codePointAt()
      res.toFixed()
  }
}

为什么当我在我的类 Test 上实现接口 ITest 时,它仍然无法推断参数类型?

【问题讨论】:

  • 我现在没有时间回答,但是请参阅stackoverflow.com/questions/58256115/… ...接口中的 implements 子句仅用作类型检查;它不参与类型推断。链接问题的答案指向围绕该问题的一些 GitHub 问题。

标签: typescript


【解决方案1】:

ITest.store 必须实现 (req: string, res: number) =&gt; void;。从技术上讲,您的测试的 store 方法可以做到这一点。它的签名是(req: any, res:any) =&gt; voidany 类型对于 stringnumber 都足够了。

当您使用implements 时,您的对象/类/等同意满足接口的要求。 这意味着界面不会对类型做出任何决定。它是实施者的责任。所以回到上面,Test 同意实现ITest 接口。它的 store 方法当前的签名为(req: any, res: any) =&gt; void。由于any 满足stringnumber 它有效地满足ITest 接口。

【讨论】:

  • 我可以做些什么来推断我的界面上的参数类型吗?
  • 不输入。但是,您已经有了一个方便的类型。 @Balastrong 有一个利用 MyFunction 类型来减少重复的例子。
  • 好的,谢谢你的回答,对我很有帮助
【解决方案2】:

store 不是函数,是具有函数类型的属性。

如果你想保留类型,你应该像这样声明它:

    class Test implements ITest {
      store: MyFunction<void> = (req, res) => {
          req.codePointAt();
          res.toFixed();
      }
    }

现在codePointAt 想要一个参数:)

【讨论】:

【解决方案3】:

我想这就是@jcalz 的意思,你仍然需要将参数和返回类型放在类方法上,但是通过实现接口,TypeScript 会检查方法是否具有与接口相同的参数和返回类型实现

type MyFunction<T> = (req: string, res: number) => T;

interface ITest {
  store: MyFunction<void>;
}

class Test implements ITest {
  store(req: number, res: number): void {
  }
}

该代码将显示错误,因为 req 类型不兼容

Property 'store' in type 'Test' is not assignable to the same property in base type 'ITest'.
  Type '(req: number, res: number) => void' is not assignable to type 'MyFunction<void>'.
    Types of parameters 'req' and 'req' are incompatible.
      Type 'string' is not assignable to type 'number'.

TS Playground

【讨论】:

  • 出现该错误是因为您的 req 类型是数字,但 MyFunction 类型使用字符串。我不相信它与原始问题有关。
  • 这就是我回答的重点,我只是澄清@jcalz 所说的话; “接口中的 implements 子句仅用作类型检查;它不参与类型推断”,它回答了“为什么我的类方法无法从其接口获取参数类型?”的问题,以及我的代码提供的(尤其是在 TS Playground 的那个)只是证明这一点的一个例子
  • 啊,我现在明白了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 2017-10-09
相关资源
最近更新 更多