# Typescript generics - how to convert c# code

**URL:** <https://forum.codewithmosh.com/t/typescript-generics-how-to-convert-c-code/13078>\
**Category:** TypeScript\
**Created:** [June 15, 2022, 6:34am UTC](https://forum.codewithmosh.com/t/typescript-generics-how-to-convert-c-code/13078 "2022-06-15T06:34:43Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Gleedo](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/gleedo/32/1297_2.png) [@Gleedo](https://forum.codewithmosh.com/u/Gleedo)\
**Post date:** [June 15, 2022, 6:34am UTC](https://forum.codewithmosh.com/t/typescript-generics-how-to-convert-c-code/13078/1 "2022-06-15T06:34:43Z")

</div>

Hi all, Sorry for posting here but there doesn’t seem to be a Typescript forum yet.

I have bought the Typescript course and tried to consume the generics section, but I still can’t quite figure this out.

I would like to do the typescript equivalent of this c# code - more specifically the getPage method using generics. Any help appreciated, especially with a comment explaining the solution 🙂

```auto
class Pages
    {
        private static T GetPage<T>() where T : new()
        {
            var page = new T();
            return page;
        }

        public static AboutPage About
        {
            get { return GetPage<AboutPage>(); }
        }
    }

```

I would also need the ‘page = new’ bit to take an argument as well.

---

<div class="post-metadata">

**Author:** ![jmrunkle](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jmrunkle/32/3765_2.png) [@jmrunkle](https://forum.codewithmosh.com/u/jmrunkle)\
**Post date:** [June 15, 2022, 7:26pm UTC](https://forum.codewithmosh.com/t/typescript-generics-how-to-convert-c-code/13078/2 "2022-06-15T19:26:02Z")

</div>

I am not sure this is possible in Typescript since not all classes would have a zero-argument constructor.

There is however, a near approximation according to [this StackOverflow question](https://stackoverflow.com/questions/17382143/create-a-new-object-from-type-parameter-in-generic-class). You take the class as an argument and type the argument with the `new` function:

```auto
function getPage<T>(type: { new(): T ;} ): T {
    return new type();
}

let aboutPage: AboutPage = getPage(AboutPage);

```

---

<div class="post-metadata">

**Author:** ![Gleedo](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/gleedo/32/1297_2.png) [@Gleedo](https://forum.codewithmosh.com/u/Gleedo)\
**Post date:** [June 18, 2022, 3:08pm UTC](https://forum.codewithmosh.com/t/typescript-generics-how-to-convert-c-code/13078/3 "2022-06-18T15:08:41Z")

</div>

Thank you for the reply @jmrunkle, I will give that a shot 🙂
