我正在使用TypeScript中的专用函数签名。我的理解是以下应该有效:
// Basic superclass and subclass
class Model { }
class Product extends Model { name: string; }
// Define interface for singleton factory class with generic create method.
interface IModels { create(type: any): Model; }
const ctors = {product: Product};
// Implement generic version of create.
class Models implements IModels {
create(type: any): Model { return new ctors[type](); }
}
// Extend interface with specialized signature.
interface IModels { create(type: "product"): Product; }
const models = new Models;
const product: Product = models.create("product");
但是,这会在最后一行产生以下错误:
Class 'Models' incorrectly implements interface 'IModels'.
Types of property 'create' are incompatible.
Type '(type: any) => Model' is not assignable to type '{ (type: any): Model; (type: "product"): Product; }'.
Type 'Model' is not assignable to type 'Product'.
Property 'name' is missing in type 'Model'.
如果我将create
的返回类型从Model
更改为any
,那么它会编译,但为什么我必须这样做?
答案 0 :(得分:1)
界面......
interface IModels { create(type: "product"): Product; }
...通过方法签名... {/ p>在您的Models
类中实现
create(type: any): Model;
...因为any
是"product"
的可接受实现。然后,编译器仅使用Models
类中的方法信息。
您还可以通过将此信息添加到Models
类以及过载签名中来消除错误:
class Models implements IModels {
create(type: "product"): Product;
create(type: any): Model;
create(type: any): Model {
return new ctors[type]();
}
}