Skip to content

A Quick Guide to Declaration Merging

Johannes Loher edited this page Dec 5, 2021 · 2 revisions

This is a community project and it might sometimes mess up. If something you're seeing behavior-wise doesn't match up with what the types are telling you, it's likely that the types are incomplete or wrong. Sometimes you'll be in a situation where an incorrect type is causing you a headache and you don't want to //@ts-ignore the problem.

This is where Declaration Merging can come in to save the day.

The official documentation is excellent and worth reading, but here's a basic gist of how to use this to work around issues with our type defs.

1. Identify a problem.

A while ago, I ran into an incorrect type in the 0.7.9 branch of this project: image

I know from looking at the data that sheetData.results here is an array, and thus must have map as a method. Looking closer you can tell that TS believes sheetData.results is typed as simply Result instead of Result[]. Time to patch that up.

2. Create a global definition file.

In your src directory, create a global.d.ts file. This .d.ts format is registered as a type definition file and won't be emitted with the rest of your project.

For some configurations of .tsconfig you might need to add this file to your includes but for the majority of setups it will be picked up automatically.

3. Find the erroneous definition.

This is going to involve a little digging, if your IDE has a "Go To Type Definition" command like VS Code does that'll make it easier. Following the definition of sheetData.results above, we arrive at the RollTableConfig definition:

namespace RollTableConfig {
  // ...
  interface Data {
    // ...
    results: RollTable.Result; // incorrect: a single result; correct: an array of results
  }
}

4. Merge the correct declaration.

Now that we know where this lives, we can overwrite just this definition (without affecting any of the other definitions) in our new global.d.ts file like so:

declare namespace RollTableConfig {
  interface Data {
    results: RollTable.Result[]; // TODO: Open issue in foundry-vtt-types detailing the bug.
  }
}

5. Success!

image

Contribute!

Once you've worked around the issue and unblocked yourself, please remember to open an Issue on this repository to detail the incorrect