简体   繁体   中英

getter/setter on a module in TypeScript

I am using AMD modules (compiler flag "--module amd") in my TypeScript project. While I can easily use getters/setters on my classes I would like to do the same on my modules but

export get abc() : string {
    return "abc";
}

returns

error TS1008: Unexpected token; 'module, class, interface, enum, import or statement' expected.

and

export function get abc() : string {
    return "abc";
}

returns

error TS1005: '(' expected.

What am I doing wrong?

You can only add getters and setters to a class at the moment.

The code transformation TypeScript uses on getters and setters adds the property to the prototype of the object, which makes more sense for classes than for modules.

This is possible, using the special export = ... syntax as follows:

class MyModule {
    get abc() {
        return "abc";
    }
}

var myModule = new MyModule();
export = myModule;

This makes an instance of the class MyModule act as the API of the module. You don't have to put any data in the class - just move your functions into it and otherwise leave them unchanged. The downside is that if function a calls function b it will have to say this.b() or myModule.b() (the latter is closer to a normal module export).

Also you have to declare a named variable first. You can't just say:

export = new MyModule(); // This doesn't work

Just for reference of future visitors ...

Similar to what @Daniel Earwicker was saying and explaining what @billc.cn was saying, you can also conflate a class with a namespace and then just define the getter/setter as a static method:

export class X {
   static get abc():string {
      return "abc";
   }
}

export namespace X {
  // ... other code
}

But this means that you will have a namespace within your library (module) and unless you want to change the way that you address attributes of your library, you will have to do the hack export = X; that @Daniel Earwicker mentioned.

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

You can export your getter directly, via a class, like this:

// helper class to be removed when/if module-level getters are available
class _someHelper {
    static get myStaticString(): string {
        return "hi, world";
    }
}

export const myStaticString = _someHelper.myStaticString;

Then import like:

import { myStaticString } from "my-module";

Not the prettiest, but it does work.

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