1

I'm trying to code my own generic iterator class with "DType" and having it a map function which can do a mapping from MyOwnIterator -> MyOwnIterator as the code below:

class MyOwnIterator<DType> {
    data:DType[]
        constructor (init:DType[]){
        this.data=init
    }
    map<AnotherDType>( func:(item:DType)=>AnotherDType):MyOwnIterator<AnotherDType>{
        return new MyOwnIterator(this.data.map(func))
    }
}
  

Now I want to write a more "generic" type for such kind of thing to make MyOwnIterator compatible with it, but how do I write? part below:

type GeneralIterator<DType, IteratorType> = {
    map: <T> (func:(item:DType)=>T) => unknown // ???
}       

I can't do IteratorType since TS compiler says IteratorType is not a generic

wonderflame
  • 6,759
  • 1
  • 1
  • 17
Zumars
  • 19
  • 3
  • Can you include the usage of `GeneralIterator` that you are expecting? Maybe some test cases so that we can have them as a reference – wonderflame May 13 '23 at 22:25
  • 1
    Sounds like you're looking for *higher kinded types* which TypeScript doesn't currently support directly (although there are ways to emulate them, but they all involve some extra boilerplate to use). See [ms/TS#1213](https://github.com/microsoft/TypeScript/issues/1213) for the relevant feature request. So there's no direct way to say that `IteratorType` is itself generic. Does that fully address your question or am I missing something? – jcalz May 13 '23 at 22:33
  • The idea is MyOwnIterator is just one of possible implementiation of a more general data structure which supports the "map" here. And the GeneralIterator is used for typing the more general data structure. The external world might have const d:GeneralIteartor = new .... This is kind of like virtual function in OOP but I want to solve this using type system rather than using OOP techniques – Zumars May 14 '23 at 00:39
  • What you're calling `GeneralIterator` is essentially a *functor* as mentioned in [ms/TS#23758](https://github.com/microsoft/TypeScript/issues/23758), and it would need higher kinded types to work. See the linked questions and answers for more information. – jcalz May 14 '23 at 00:55

0 Answers0