Search code examples
typescriptclassgenericstypesinterface

type or interface inside class in typescript


I have a generic class that uses another derivative type (based on that generic type). I'd like to define the derivative type inside the class so I do not have to write it every time but TypeScript throws me an error.

current version (working):

class MyClass<T> {
    t: T

    doSomeThing(f: (t: T) => void) {}

    doAnotherThing(g: (t: T) => void) {} 
}

The version I want (not working):

class MyClass<T> {
    static type FT = (t: T) => void
    // throws error: I can't define type or interface inside class
    
    t: T

    doSomeThing(f: FT) {}

    doAnotherThing(g: FT) {} 
}

What is the right approach and solution. Thanks.


Solution

  • You may use a declared prop, or maybe a namspace

    class MyClass<T> {
        // it's instance property. It does not exists actually.
        declare readonly FT: (t: T) => void;
        
        doSomeThing(f: typeof this.FT) {}
        doAnotherThing(g: MyClass.FT<T>) {} 
    }
    declare namespace MyClass {
        export type FT<T> = (t: T) => void
    }
    
    new MyClass<123>().doSomeThing
    //                 ^?
    // (method) MyClass<123>.doSomeThing(f: (t: 123) => void): void
    
    new MyClass<123>().doAnotherThing
    //                 ^?
    // (method) MyClass<123>.doAnotherThing(g: (t: 123) => void): void