【发布时间】:2020-05-10 12:21:32
【问题描述】:
我正在使用 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,那么它会编译,但为什么我必须这样做?
【问题讨论】:
标签: typescript