简体   繁体   中英

Singleton decorator in typescript

I'm trying to use this code:

function singleton<T extends { new() }>(constructor: T): T {
    return new constructor()
}

@singleton
export default class SomeClass {
    constructor() {}

    public method(): string {
        return 'Hello!'
    }
}

console.log(SomeClass.method())

And it works. The message "Hello!" is displayed in the console. But the typescript compiler says there's error: 在此处输入图片说明

What's wrong?

Unfortunately the compiler cannot know what changes the decorator does to the class. You could try something like this:

function singleton<T>(constructor: new ()=> T): T {
    return new constructor()
}

export const SomeClass = singleton(class  {
  constructor() {}

  public method(): string {
      return 'Hello!'
  }
});

console.log(SomeClass.method())

Just use new before your class declaration:

export default new class {
  constructor() {}

  public method(): string {
      return 'Hello!'
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM