noobiePT
noobiePT

Reputation: 115

Generic constraint of the same type

I have this class:

class Container {
    parent: any;
    children: any[];
}

I want to remove the 'any' types, and that can be done with generics. The problem I have is that the 'any' types are also off the 'Container' type, which will require to specify the generic types again.

class Container<P extends Container<?>, C extends Container<?>> {
    parent: P;
    children: C[];
}

How can I tell that the constraint is the same class type?

Upvotes: 0

Views: 209

Answers (2)

Duncan
Duncan

Reputation: 95752

I think it is sufficient here to say that P extends Container<any,any> and C extends Container<any,any>:

class Container<P extends Container<any,any>,C extends Container<any,any> >{
    parent: P;
    children: C[];
}

class Parent extends Container<Parent,Child> {
  name: string;
}

class Child extends Container<Parent, Child> {
  childname: string;
}

const root = new Parent();
root.parent;
root.children[0].parent;
root.name;
root.children[0].childname;

The syntax checking in the editor correctly works out here the types of all the values at the end.

Upvotes: 1

Benjamin Hodgson
Benjamin Hodgson

Reputation: 44664

I don't know what your use case looks like exactly, but how about this simple version of your class?

class Container<T> {
    parent: Container<T>;
    children: Container<T>[];
}

Upvotes: 1

Related Questions