没有构造函数的打字稿工厂

Typescript factory without constructor

我最近遇到了以下代码:

class PizzaMaker {
    create(event: { name: string; toppings: string[] }) {
        return { name: event.name, toppings: event.toppings };
    }
}

const pizzaMaker = new PizzaMaker();

const pizza = pizzaMaker.create({
    name: 'Inferno',
    toppings: ['cheese', 'peppers'],
});

console.log(pizza);
// Output: { name: 'Inferno', toppings: [ 'cheese', 'peppers' ] }

如何在没有构造函数的情况下实例化 PizzaMaker?

在任何支持原生 类 的环境中(例如 ES6 及更高版本),如果未提供构造函数,则会自动生成:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor

If you don't provide your own constructor, then a default constructor will be supplied for you. If your class is a base class, the default constructor is empty.

对于不支持原生 类 的环境(例如 ES5 和之前的版本),TypeScript 会为您生成默认构造函数:

来自the playground

class PizzaMaker {
    create(event: { name: string; toppings: string[] }) {
        return { name: event.name, toppings: event.toppings };
    }
}

发出JavaScript:

"use strict";
var PizzaMaker = /** @class */ (function () {
    // Note: this empty function is the default constructor
    function PizzaMaker() {
    }
    PizzaMaker.prototype.create = function (event) {
        return { name: event.name, toppings: event.toppings };
    };
    return PizzaMaker;
}());