Typing

If you are using TypeScript in your project, you can leverage LiveObjects’ built-in TypeScript support to ensure type safety and enable autocompletion when working with objects on a channel.

You can type objects on all your channels by defining a global ObjectsTypes interface. If you only want to type the root object for a specific channel, see the Typing channel.objects.getRoot() section below.

Define the ObjectsTypes interface in a type declaration file. You can create a file named ably.config.d.ts in the root of your application:

JavaScript v2.9
// file: ably.config.d.ts import { LiveCounter, LiveMap } from 'ably'; // Define dedicated types and export them for reuse in your application export type MyCustomRoot = { reactions: LiveMap<{ hearts: LiveCounter; likes: LiveCounter; }>; }; declare global { export interface ObjectsTypes { root: MyCustomRoot; } }
Copied!

This enables TypeScript to infer the correct types when accessing and mutating LiveObjects:

JavaScript v2.9
// LiveMap<{ reactions: LiveMap<{ hearts: LiveCounter; likes: LiveCounter }> }> const root = await channel.objects.getRoot(); // LiveMap<{ hearts: LiveCounter; likes: LiveCounter }> const reactions = root.get('reactions'); // LiveCounter const likes = reactions.get('likes'); reactions.set('hearts', 1); // Error: Argument of type 'number' is not assignable to parameter of type 'LiveCounter'.ts(2345)
Copied!

You can pass a type parameter directly to the channel.objects.getRoot<T>() method call to type the root object for a channel explicitly:

JavaScript v2.9
// Define types for different root objects type ReactionsRoot = { hearts: LiveCounter; likes: LiveCounter; }; type PollsRoot = { currentPoll: LiveMap; }; // LiveMap<{ hearts: LiveCounter; likes: LiveCounter }> const reactionsRoot = await reactionsChannel.objects.getRoot<ReactionsRoot>(); // LiveMap<{ currentPoll: LiveMap }> const pollsRoot = await pollsChannel.objects.getRoot<PollsRoot>();
Copied!

Typing channel.objects.getRoot<T>() is particularly useful when your application uses multiple channels, each with a different object structure.

Select...