简体   繁体   English

TypeScript 中的特殊函数签名

[英]Specialized function signatures in TypeScript

I am working with specialized function signatures in TypeScript.我正在使用 TypeScript 中的专门函数签名。 My understanding is that the following should work:我的理解是以下应该有效:

// 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");

However, this yields the following error on the last line:但是,这会在最后一行产生以下错误:

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'.

If I change the return type of create from Model to any , then it compiles, but why should I have to do that?如果我将create的返回类型从Model更改为any ,那么它会编译,但为什么我必须这样做?

The interface...界面...

interface IModels { create(type: "product"): Product; }

...is implemented in your Models class by the method signature... ...通过方法签名在您的Models类中实现...

create(type: any): Model;

...since any is an acceptable implementation of "product" . ...因为any是可接受的"product" The compiler then only uses the method information from the Models class.然后编译器只使用来自Models类的方法信息。

You can also get rid of your error by adding this information to your Models class as well in an overload signature:您还可以通过将此信息添加到Models类以及重载签名中来消除错误:

class Models implements IModels {
    create(type: "product"): Product;
    create(type: any): Model;
    create(type: any): Model {
        return new ctors[type]();
    }
}

Update 2020 2020 年更新

Nowadays, you would most likely write something along these lines:如今,您很可能会按照以下方式写一些东西:

const ctors = { product: Product };

class Models {
  create(type: keyof typeof ctors): Model {
    return new ctors[type]();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM