I have used declaration merging as follows
function barfoo(): void { /* magic */ }
namespace barfoo {
export let maz: Array<string> = [];
}
But the question is, how can I use this. For example, if I use it as follows
function doIt(cb: barfoo): void {
cb.maz = [10];
cb();
}
typescript is complaining: Cannot find name 'barfoo'.
Any suggestions how to fix the type (without using any
:) ?
UPDATE: I figured out how to create new functions of this type
let x: { (): Array<string>; maz: Array<string>; };
x = (() => {
var _x : any = function () { };
_x.maz = [];
return _x;
})();
let y: { (): void; maz: Array<string> } = (() => {
let _y: any = function fake(): Array<string> {
return ((cb: any): Array<string> => {
return cb.maz;
})(fake);
}
_y.maz = [];
return _y;
})();
But, as you can see, the second example is very complex. Is this the correct way or can this be simplified?
Your problem is that barfoo
is a value, but in your definition of doIt()
you are mistakenly treating it as a type. All values have a type, but the name of a value is rarely the name of its type. If I do let x = 3;
then x
is a value, but its type is number
, not x
.
It seems from your code you want to be able to pass in the value barfoo
to the function. (Why you would want to do such a thing is your business, but if you're only ever going to pass that one value into the function, you might want to consider not having it be a parameter at all. Up to you, though.) So the cb
parameter should be declared to be the type of barfoo
, whatever it is. By inspection you can see it is something like { (): void; maz: string[] }
. But luckily TypeScript allows you to quickly get the type of a named value by using a type query, which reuses the keyword typeof
. The type of barfoo
is simply typeof barfoo
:
function doIt(cb: typeof barfoo): void {
cb.maz = [10]; // error, hey 10 is not a string
cb();
}
This works, and even catches another bug for you. Hope that helps; good luck!
If you want to make more objects of the same type as barfoo
, that is: a callable function (of no arguments and returning void
) which also has a maz
property containing an array of strings, the most straightforward way to do it is to use Object.assign()
, which merges all properties into the first argument and returns it as the intersection of all the argument types. Like this:
const barfoo2 = Object.assign(
function() {
// function body here
},
{maz: ["some","stuff"]}
);
doIt(barfoo2); // works
Good luck again!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments