torazaburo torazaburo -4 years ago 118
TypeScript Question

Excessive stack depth comparing types 'Snapshot<T>' and 'DataSnapshot'. [2321]

I am trying to define type-safe versions of some Firebase database constructs, starting with snapshots, so I wrote:

interface Snapshot<T> extends firebase.database.DataSnapshot {
val(): T;
}


So far so good. Now, I want to define the
child
method, which returns a snapshot of a node's child, in type-safe fashion, so:

interface Snapshot<T> extends firebase.database.DataSnapshot {
val(): T;
child<U extends keyof T>(path: U): Snapshot<T[U]>;
}


In other words, the parameter to
child
is a string which is a property on
T
, and it returns a snapshot of that property's type. However, this gives me the error:


Excessive stack depth comparing types 'Snapshot' and 'DataSnapshot'. [2321]


What is the problem, and how can I write this?

Answer Source

The error occurs because the return type of the child method in the firebase.database.DataSnapshot is that of its enclosing interface. And that does not appear to play nice with your typesafe interface declaration.

The following is a minimal reproduction of the problem:

interface DataSnapshot {
  child(path: string): DataSnapshot;
}

interface Snapshot<T> extends DataSnapshot {
  child<U extends keyof T>(path: U): Snapshot<T[U]>;
}

If the return type of DataSnapshot is changed, the error is not raised:

interface DataSnapshot {
  child(path: string): any;
}

interface Snapshot<T> extends DataSnapshot {
  child<U extends keyof T>(path: U): Snapshot<T[U]>;
}

There does not appear to be anything wrong with your interface declaration. I would call this a TypeScript bug.

Interestingly, you can work around the bug by shoving another interface between Snapshot<T> and DataSnapshot:

interface DataSnapshot {
  child(path: string): DataSnapshot;
}

interface DataSnapshotAsAny extends DataSnapshot {
  child(path: string): any;
}

interface Snapshot<T> extends DataSnapshotAsAny {
  child<U extends keyof T>(path: U): Snapshot<T[U]>;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download