简体   繁体   中英

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?

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>[];
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM