typescript - 使用泛型时,Typescript 无法识别错误
问题描述
当我使用以下代码时,打字稿不会抱怨我尝试通过IAction<Product>
而不是预期的IAction<Customer>
:
interface IAction<T> {
canExecute<T>(input: T): void;
}
interface Product {
name: string,
}
interface Customer {
displayName?: string;
description?: string;
}
class MyAction implements IAction<Product> {
public canExecute<Product>(product: Product): void {
}
}
class MyMenuItemAction {
constructor(private action: IAction<Customer>) {
}
}
function foo(action: IAction<Customer>): void {
}
const action: IAction<Product> = new MyAction();
const menuItem = new MyMenuItemAction(action);
foo(action);
但是如果我<T>
从 IAction 接口的 canExecute 函数中删除它,它确实会抱怨它:
interface IAction<T> {
canExecute(input: T): void;
}
这是打字稿中的错误吗?
解决方案
您需要更改界面以避免覆盖泛型
interface IAction<T> {
canExecute(input: T): void; // <- remove <T> from here.
// canExecute<T> means there's another generic that has a conflict
// with IAction<T>
}
然后更新 MyAction
class MyAction implements IAction<Product> {
public canExecute(product: Product): void { // <- remove <Product>
}
}
利润:游乐场
推荐阅读
- javascript - 如何在for循环中禁用正确的按钮
- https - Jetty https 模块导致启动失败
- mysql - 我对聚集索引在 Innodb 中的工作方式有疑问
- python - 如何使用 python 脚本提取包含多个部分的 zip 文件以在 Google Cloud Function 中运行
- vim - 无论如何关闭/退出活动选项卡
- docker - AWS S3 和 AWS Elastic Beanstalk 之间的关系(多 docker env)
- python - 尝试从上传到 Google colab 的 CSV 中绘制数据时出现语法错误
- python - 如何制作一个在需要时专门更新的 Python 属性对象?
- mongodb - 如何同步或迁移猫鼬?
- google-earth-engine - 如何将图像集合剪辑到特征集合的几何图形