Typescript: how to user typescript genericity like the C#

Created on 17 Jan 2018  路  5Comments  路  Source: microsoft/TypeScript

public class Singleton where T: class,new()
{
private static T _instance;
private static readonly object syslock=new object();

public static T getInstance()   
{  
    if (_instance == null)  
    {  
        lock (syslock) {  
            if (_instance == null)  
            {  
                _instance = new T();  
            }  
        }  
    }  
    return _instance;  
}

}

how to user typescript to write this?

Question

Most helpful comment

Please do not use our issue tracker for questions in the future, as StackOveflow is a more well-suited venue.

All 5 comments

In typescript. there is no new T(). how could I do this?

JavaScript has a different execution model than C#. In particular, there are no threads. So patterns you used in C# may not be applicable any more. You may want to study up on the JavaScript language to learn the different ways things are done.
In this case, instead of using the singleton pattern to expose a value, you can just export it as a value like so:

definition.ts

export const myValue = { /*...object contents here...*/ };

user.ts

import { myObject } from "./definition";

Not that I think this is a good idea, but just for reference, a more direct translation of what you're trying might look like this:

function lazyInstanceGetter<T>(cls: new () => T): () => T {
    let value: T | undefined;
    return () => {
        if (value === undefined) {
            value = new cls();
        }
        return value;
    };
}

class C {}
const cGetter = lazyInstanceGetter(C);
const theC = cGetter();

But you probably don't actually need lazy initialization, so I would recommend just export const theC = new C(); (or forget the class and just use an object literal) instead.

Please do not use our issue tracker for questions in the future, as StackOveflow is a more well-suited venue.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings