---
# System prepended metadata

title: Typescript - Using Class Types in Generics
tags: [generics, typescript]

---

# Typescript - Using Class Types in Generics
Source
https://www.typescriptlang.org/docs/handbook/2/generics.html


## Example
- The constructors of `ClassA` and `ClassB` both take string arguments during object creation
- The function `getClassInstance` has two parameters, one is a string parameter for object creation. The other is the class type for the constructor

```
class ClassA {
    private myName: string;

    constructor(name: string){
        this.myName = name;
    }

    public get name(): string {
        return this.myName;
    }
}


class ClassB {
    private myName: string;

    constructor(name: string){
        this.myName = name;
    }

    public get name(): string {
        return this.myName;
    }
    
    public get currentDate(): Date {
        return new Date();
    }
}


function getClassInstance <Type>(newName: string, classType: { new (name: string): Type }): Type {
    const classInstance = new classType(newName);
    return classInstance;
}

const classAInstance = getClassInstance('testA', ClassA)
console.log(classAInstance.name);

const classBInstance = getClassInstance('testB', ClassB)
console.log(classBInstance.name);
```






###### tags: `typescript` `generics`