-
Notifications
You must be signed in to change notification settings - Fork 56
FAQ
Johannes Loher edited this page Dec 5, 2021
·
9 revisions
- How do I make the Foundry VTT Types recognize the data layout I have defined in my
template.json
file? - I'm using a custom document class, how do I make the Foundry VTT Types recognize that?
- Why can't I access any properties on
game
/canvas
? - How do I create my own
FormApplication
?
How do I make the Foundry VTT Types recognize the data layout I have defined in my template.json
file?
Take a look at Actors and Items which includes detailed instructions regarding that.
Take a look at Custom Document Class Configuration which includes detailed instructions regarding that.
Foundry VTT initializes these global variables right before the 'init'
hook event. However, it is possible for modules / systems to access these variables in code that runs before the 'init'
hook event (code that runs on the module / script level), so we need to include their uninitialized states in their types. To mitigate this, there are a couple solutions:
- Add a type guard when trying to access these variables:
if(game instanceof Game) { // whatever you wanted to do with `game` } else { throw new Error('game not initialized yet!'); }
- It is cumbersome to do this at every place where you want to access these variables. A solution for that is to create a wrapper around the variable you want to access, do the type guarding in there, and then just use the wrapper in the rest of your code instead of using the variable directly:
function getGame(): Game { if(!(game instance of Game)) { throw new Error('game is not initialized yet!'); } return game; } // somewhere else in your code: getGame().i18n.localize('...'); // or whatever else you wanted to do with game
- If this is still to cumbersome to you, there is another way out: We added a way to configure a couple of global vaiables to be typed as their initialized states with the help of declaration merging (see A Quick Guide to Declaration Merging for a short introduction on what that is and on how you can use it to work around possible mistakes in the type definitions). All you need to do is globally declare the interface
LenientGlobalVariableTypes
with properties called like the variables that you want to be typed more leniently (the types of the properties don't matter). Currently, the variablesgame
,socket
,ui
andcanvas
are supported. Here is an example that shows how to do this forgame
:declare global { interface LenientGlobalVariableTypes { game: never; // the type doesn't matter } } game.i18n.localize('...'); // or whatever else you want to do with game, works fine now! :)
⚠️ If you use this method, be aware that the compiler won't help you if you try to access these variables before they are actually initialized, so you have to make sure yourself that this doesn't happen!
Take a look at Creating custom FormApplications.