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.

Global AblyObjectsTypes interface

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

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

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// 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 AblyObjectsTypes {
    root: MyCustomRoot;
  }
}

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

JavaScript

1

2

3

4

5

6

7

8

9

10

// 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)

Typing channel.objects.getRoot()

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// 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>();

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

Select...