【问题标题】:How can I make a type of the anonymous function?我怎样才能创建一个匿名函数的类型?
【发布时间】:2023-02-05 13:49:08
【问题描述】:

我要创建类型的函数如下(scratch-parser 的一部分):

module.exports = function (input, isSprite, callback) {
    // Unpack the input and further transform the json portion by parsing and
    // validating it.
    unpack(input, isSprite)
        .then(function (unpackedProject) {
            return parse(unpackedProject[0])
                .then(validate.bind(null, isSprite))
                .then(function (validatedProject) {
                    return [validatedProject, unpackedProject[1]];
                });
        })
        .then(callback.bind(null, null), callback);
};

我为这个函数创建了一个类型,但是这个函数是匿名的,所以我不能断言这个类型。

declare function scratchParser(
  input: Buffer | string,
  isSprite: boolean,
  callback: (
    err: Error,
    project: ScratchParser.Project | ScratchParser.Sprite,
  ) => void,
): void;

如何通过module.exports断言匿名函数的类型?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    使用declare 不太正确,因为这表明 JavaScript 中存在具有该名称的函数。但是您想要的是 module.exports 函数的类型,用于与 - 或 satisfy 进行比较。

    scratchParser设为type,并指明导出的函数satisfies为该类型。

    type scratchParser = (
      input: number | string,
      isSprite: boolean,
      callback: (
        err: Error,
        project: ScratchParser.Project | ScratchParser.Sprite,
      ) => void,
    ) => void;
    
    module.exports = function (input, isSprite, callback) {
        // Unpack the input and further transform the json portion by parsing and
        // validating it.
        unpack(input, isSprite)
            .then(function (unpackedProject) {
                return parse(unpackedProject[0])
                    .then(validate.bind(null, isSprite))
                    .then(function (validatedProject) {
                        return [validatedProject, unpackedProject[1]];
                    });
            })
            .then(callback.bind(null, null), callback);
    } satisfies scratchParser;
    // ^^^^^^^^^^^^^^^^^^^^^^
    

    【讨论】:

      猜你喜欢
      • 2011-04-27
      • 1970-01-01
      • 2017-08-11
      • 2017-07-01
      • 2018-03-25
      • 2020-01-17
      • 2017-07-06
      • 2022-10-24
      • 2023-03-14
      相关资源
      最近更新 更多