Typescript generics - how to convert c# code

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 :slight_smile:

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.

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. You take the class as an argument and type the argument with the new function:

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

let aboutPage: AboutPage = getPage(AboutPage);

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

1 Like