Search code examples
typescriptgenericsconstraintstype-traits

TypeScript: Implementing a generic type-constrained function to instantiate and return instances of a specific type


I want to implement a function with the following behavior:

GetComponent<T>(type : typeof T): T { ... } 

I would like this function to accept a constructor as an argument, where the constructor's type is T, and return an instance of type T.

Additionally, I want the function to result in a compilation error if the provided type does not match. (like GetComponent<Vec2>(Vec3)).

Is it possible to achieve this functionality?

And if there is any way to forbid the abstracted type to input?

i had try something like this:

class Resources {
    static Load<T extends AssetObject>(type: typeof AssetObject, id: string): T {
        return Resources.load_sync_impl(id, type) as T;
    }
}

but when i try to write List, and i can not find any way to limit the input argument as the type i define in the class:

class List<T> {
    constructor(type: any) {   <<======= i had to write it as any so it can support the private constructor class
        this._type = type;
    }
}

the old solution is something like

constructor(type: new (...args: any[]) => T);

Solution

  • i finally found the answer for this question, here is it

    type Traits_Constructor<T> = T extends Function ? Function : (Function & { prototype: T });
    

    and use this trait directly, then problem sloved!

    GetComponent<T extends Component>(type: Traits_Constructor<T>): T;