如何在TypeScript中正确创建泛型方法?

如何在TypeScript中正确创建泛型方法?,typescript,generics,Typescript,Generics,我有一个抽象类: abstract class TableAdapter { public abstract convertInputToOutput<InputType, OutputType> (apiRow: InputType): OutputType; } 我在编译时看到一个错误: 参数“apiRow”和“apiRow”的类型不兼容。 类型“ApiRowType”不可分配给类型“InputType1” 如何修复它并在继承类中设置确切的类型,以便访问对象的字段?尝试

我有一个抽象类:

abstract class TableAdapter {
    public abstract convertInputToOutput<InputType, OutputType> (apiRow: InputType): OutputType;
}
我在编译时看到一个错误:

参数“apiRow”和“apiRow”的类型不兼容。 类型“ApiRowType”不可分配给类型“InputType1”


如何修复它并在继承类中设置确切的类型,以便访问对象的字段?

尝试扩展泛型类,将抽象类修改为
抽象类TableAdapter
并像
类TableAdapter 1 Extendes TableAdapter
那样扩展TableAdapter 1

抽象类TableAdapter{
公共抽象ConvertInputOutput(apiRow:InputType):OutputType;
}
类TableAdapter1扩展了TableAdapter{
公共ConvertInputOutput(apiRow:InputType1):输出Type1{
}
}
类TableAdapter2扩展了TableAdapter{
公共ConvertInputOutput(apiRow:InputType2):输出Type2{
}
}

关于TypeScript的一个有趣的事情是,在标称语言中,许多需要使用泛型的情况都可以在没有TypeScript的情况下处理

这并不是说您的特定场景可以在没有泛型的情况下完成,但值得考虑下面的示例

如果您有一个所有输入类型和输出类型都必须遵守的最小接口,那么由于结构类型系统,您可以在没有泛型的情况下实现这一点

例如,如果您需要输入类型以最小限度地具有
name
,但它也可以具有其他属性,则可以在不使用泛型的情况下实现这一点。例如,我们将使用几个接口,但您不一定需要这些-结构就可以了。。。输出类型也是如此

interface InputType {
    name: string;
}

interface InputType1 extends InputType {
    location: string;
}

interface InputType2 {
    name: string;
}
将检查代码的结构兼容性,而不需要泛型:

abstract class TableAdapter {
    public abstract convertInputToOutput(apiRow: InputType): OutputType;
}

class TableAdapter1 extends TableAdapter {
    public convertInputToOutput(apiRow: InputType1): OutputType1 {
        return { name: '', location: '' };
    }
}

class TableAdapter2 extends TableAdapter {
    public convertInputToOutput(apiRow: InputType2): OutputType2 {
        return { name: '' };
    }
}
Any如果您对输入和输出类型感到高兴,那么抽象类可以说它对它们是
Any
类型感到高兴

interface InputType {
    name: string;
}

interface InputType1 extends InputType {
    location: string;
}

interface InputType2 {
    name: string;
}
abstract class TableAdapter {
    public abstract convertInputToOutput(apiRow: InputType): OutputType;
}

class TableAdapter1 extends TableAdapter {
    public convertInputToOutput(apiRow: InputType1): OutputType1 {
        return { name: '', location: '' };
    }
}

class TableAdapter2 extends TableAdapter {
    public convertInputToOutput(apiRow: InputType2): OutputType2 {
        return { name: '' };
    }
}