Skip to content

Commit 76b4167

Browse files
author
Philipp Molitor
committed
add module augmentation docs
1 parent 8865021 commit 76b4167

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,3 +181,57 @@ export async function fetchLoaderConfig(
181181
```
182182

183183
You can then use it to construct a `UnityContext` and pass this context to your `UnityRenderer` via the `context` prop.
184+
185+
## Module augmentation
186+
187+
Take the following example:
188+
189+
```typescript
190+
// create some context
191+
const ctx = new UnityContext({ ... });
192+
193+
// handles some "info" event with one parameter of type string
194+
ctx.on('info', (message: string) => {
195+
console.log(message);
196+
});
197+
```
198+
199+
The parameter `message` has to be explicitly defined as `string` each time a handler of for the event name `info` would be registered.
200+
In order to make use of TypeScript to its fullest extent, you can augment an Interface of the library to get autocompletion and type-safety features here.
201+
202+
Put this either in a file importing `react-unity-renderer` or create a new `unity.d.ts` somewhere in your `src` or (if you have that) `typings` directory:
203+
204+
```typescript
205+
// must be imported, else the module will be redefined,
206+
// and this causes all sorts of errors.
207+
import 'react-unity-renderer';
208+
209+
// module augmentation
210+
declare module 'react-unity-renderer' {
211+
// this is the interface providing autocompletion
212+
interface EventSignatures {
213+
// "info" is the event name
214+
// the type on the right side is anything that would match TypeScript's
215+
// Parameters<> helper type
216+
info: [message: string];
217+
218+
// also possible:
219+
info: [string];
220+
'some-event': [number, debug: string];
221+
// note that all parametrs names are just labels, so they are fully optional.
222+
}
223+
}
224+
```
225+
226+
Now, any defined event will be auto-completed with its types for `UnityContext.on(...)`:
227+
228+
```typescript
229+
// create some context
230+
const ctx = new UnityContext({ ... });
231+
232+
// "info" will be suggested by your IDE
233+
// "message" is now of type string
234+
ctx.on('info', (message) => {
235+
console.log(message);
236+
});
237+
```

0 commit comments

Comments
 (0)