The function that I want to make a type is below (a part of 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);
};
I created a type for this function, but the function is anonymous, so I cannot assert the type.
declare function scratchParser(
input: Buffer | string,
isSprite: boolean,
callback: (
err: Error,
project: ScratchParser.Project | ScratchParser.Sprite,
) => void,
): void;
How can I assert the type of anonymous function by module.exports
?
CodePudding user response:
Using declare
isn't quite right, because that indicates that a function with that name exists in the JavaScript. But what you want is a type for the module.exports
function to be compared to - or to satisfy.
Make scratchParser
a type
, and indicate that the exported function satisfies
that type.
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;
// ^^^^^^^^^^^^^^^^^^^^^^