Crafty as function vs object

41 views
Skip to first unread message

SneakBug8

unread,
Jan 6, 2019, 6:28:02 PM1/6/19
to Crafty
I was trying to write definitions for TypeScript for CraftyJS (for own use firstly), but I have a problem caused by developer's choose of using same named Crafty global object and Crafty() function. TypeScript, on the other side, blocks me from using same name for class and function in definitions file, so, maybe, developer should rename Crafty function for something like Crafty.s() for better usage? I think it's really bad practice of naming different things the same name.

I was able to surpass this issue by making small helpers.js file and defining it's only function in my d.ts file, but it's not very good.

function CraftySearch(component) {
return Crafty(component);
}

declare function CraftySearch(component : string) : Array<any>

SneakBug8

unread,
Jan 6, 2019, 6:32:00 PM1/6/19
to Crafty
Btw, whole components system makes it difficult to use with classes as my base class for CraftyEntity should declare functions from all Crafty's components like 2D and Gravity. I could write a Factory, which would return me object with good class, but TS don't support multiple inheritance.

SneakBug8

unread,
Jan 6, 2019, 6:39:52 PM1/6/19
to Crafty
Oh. And the third usage of Crafty() - get entity by id with number as argument. Sounds unresolvable for proper TS definitions

starwed

unread,
Jan 6, 2019, 7:19:23 PM1/6/19
to Crafty
I think it's going to be tricky to use typescript without a lot of manual casting -- components can be dynamically added or removed from entities. 

The specific issues you've run into are solvable, though!

> I was trying to write definitions for TypeScript for CraftyJS (for own use firstly), but I have a problem caused by developer's choose of using same named Crafty global object and Crafty() function.

Yeah, I'm not a huge fan of this -- it's an old design decision copied from jQuery, which does the same thing.

However, the pattern is common enough in js libraries that typescript does support it.  Check out this SO answer: https://stackoverflow.com/a/41853194/460138
(There are a few alternatives given in other answers, but the one I'm linking to seemed simplest.)

> the third usage of Crafty()  [...] Sounds unresolvable for proper TS definitions

TS supports function overloading, even when combined with the above approach.


> TS don't support multiple inheritance.

It does support other paradigms, however, which I'd think are a more accurate match for components in any case.  For instance, check out the page on mixins https://www.typescriptlang.org/docs/handbook/mixins.html
Reply all
Reply to author
Forward
Message has been deleted
0 new messages