首页 > 解决方案 > 使用泛型时,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;
}

这是打字稿中的错误吗?

标签: typescriptgenerics

解决方案


您需要更改界面以避免覆盖泛型

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>
    }
}

利润:游乐场


推荐阅读