interface Filter {
rowAddRow: (treeData:Tree[],id:string,filterType:FilterType) =>Tree[]
}
class FilterAction implements Filter {
// 这里还需要重新定义接口,如id的类型为string
rowAddRow(treeData:Tree[], id, filterType):Tree[] {
// todo sth
}
}
class Component {
constructor(props) {
super(props)
this.actions = new FilterAction()
}
// 这里还需要定义一遍
private actions: {
rowAddRow: (treeData:Tree[],id:string,filterType:FilterType) =>Tree[]
}
handleAdd() {
this.actions.rowAddRow()
}
}
问题 1
既然我在implements实现了rowAddRow的接口定义,为什么在class里面还需要重新定义rowAddRow的接口,否则其类型默认为any
问题 2
implements 的作用和意义到底是什么
问题 3
如何做,只需要定义一遍rowAddRow,使得他在class里面以及它的实例里面都会有这样的类型推论。不是export导出那种哈。
我的理解
既然在FilterAction里面定义了rowAddRow方法的传参要求和返回类型,那么在它的实例里面使用时,应当自动会有这个方法,且该方法拥有之前规定的接口类型,不需要重新定义
我认为interface更像是ts的header file,它的结构就好像C语言的头文件(.h)与代码文件(.c).
这样做的好处有以下几点:
- 让编译器开发人员更容易
- 可以共享接口给其他的开发者, 当需要共享接口时,选择共享interface可以保护内部逻辑不被暴露
说回到TS中, 我觉得这样设计的原因应该也是为了开发者进行工程化构建.
那么如果不想写那么多遍function定义有没有什么办法? 当然有.
你可以通过编辑器来解决. 以 VS Code 为例:
Why does C++ need a separate header file?
Should C++ eliminate header files?