首页 > 解决方案 > 使用接口的打字稿类方法定义

问题描述

我有一个从其他包导出的接口,我需要使用类来实现它。但是打字稿不能自动推断参数类型。有没有办法通过 ts 自动获取方法参数?

interface Interface {
    hello(param: {a: number}): void
}

class A implements Interface {
    hello(param) { // param is any
// how can i get the param type automatically ? 
    }
}


const B : Interface  = {
    hello(param) {// {a: number}

    }
}

标签: typescript

解决方案


https://www.typescriptlang.org/docs/handbook/2/classes.html#cautions提到了这个问题。直接从文档引用:

一个常见的错误来源是假设一个 implements 子句会改变类类型——它不会!

interface Checkable {
  check(name: string): boolean;
}
 
class NameChecker implements Checkable {
  check(s) {
// Parameter 's' implicitly has an 'any' type.

    // Notice no error here
    return s.toLowercse() === "ok";
                 
// any
  }
}

在这个例子中,我们可能期望s's 的类型会受到name: stringcheck 参数的影响。它不是 -implements子句不会更改检查类主体或推断其类型的方式。


推荐阅读