typescript - 使用接口的打字稿类方法定义
问题描述
我有一个从其他包导出的接口,我需要使用类来实现它。但是打字稿不能自动推断参数类型。有没有办法通过 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}
}
}
解决方案
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: string
check 参数的影响。它不是 -implements
子句不会更改检查类主体或推断其类型的方式。
推荐阅读
- python-3.x - 替换列中值的最佳python数据结构?
- regex - 多个匹配正则表达式正前瞻
- python - 在python中将垂直表格转换为水平表格(展平表格)
- octobercms - 如何更改rainlab.user::mail.invite 以获得激活链接
- python-3.x - Jupyter 的选项卡自动完成功能不适用于 sklearn、numpy、seaborn、pandas 和 matplotlib 等多个库
- keras - 在 Keras 中,在我自己的模型上使用 include_top= False 会删除所有最后一个密集层,我可以定义模型的“顶部”吗?
- asp.net - 无法让 ASP.NET/IIS 使用自定义缓存控制设置来提供 .js 文件
- laravel - Laravel 网站域名将转到 public/publc url
- django - django 具有相同外键的多个模型
- python - 使用 psycopg2 在 PostgreSQL 中使用密码创建用户时出错