Forward Declarations

2 min read

2 min read

Interfaces and classes can be forward declared, so that you can use them before their definition. This lets you write definitions that refer to each other, for example:

Slice
module Family
{
interface Child; // Forward declaration
sequence<Child*> Children;
interface Parent
{
Children getChildren();
}
interface Child // Definition
{
Parent* getMother();
Parent* getFather();
}
}

You can use a forward-declared class, or the proxy type of a forward-declared interface, as the element type of a sequence, the value type of a dictionary, the type of a field, and the type of an operation parameter or return value.

You can extend a forward-declared class or interface only after its definition:

Slice
interface Base; // Forward declaration
interface Derived1 extends Base {} // Error!
interface Base {} // Definition
interface Derived2 extends Base {} // OK, definition was seen

A forward declaration maps to a C++ forward declaration.

A forward declaration maps to nothing.

When a forward-declared class or interface is defined in another Slice file, add the js:defined-in metadata to the forward declaration to give that file's relative path, starting with ./ or ../. The Slice-to-JavaScript compiler imports the type from the corresponding generated module in the TypeScript declarations.

For example:

Greeter.ice
module VisitorCenter
{
["js:defined-in:./Admin.ice"]
interface GreeterAdmin;
interface Greeter
{
GreeterAdmin* getAdminObject();
string greet(string name);
}
}
Admin.ice
#include "Greeter.ice"
module VisitorCenter
{
interface GreeterAdmin
{
Greeter* getGreeter();
void shutdown();
}
}