- How to export a class instance in typescript
- Typescript: Export instance of class that holds state
- Why is it not possible to export a class instance in TypeScript?
- Future
- Export a TypeScript class from another file than it has been defined in
- In typescript, how to export the type of a private class without exporting class itself
- Typescript export class instance
- Импорт
- Псевдонимы
- Импорт всего модуля
- Экспорт по умолчанию
How to export a class instance in typescript
Solution 3: On https://k94n.com/es6-modules-single-instance-pattern is an additional way of doing this: Which has the advatage that it is possible to export several class instances in a *.ts file. Solution 1: In this example is the type of the constructor function
Typescript: Export instance of class that holds state
This should be simple, right?
class MyStore < . >// export a single instance export = new MyStore(. );
Unfortunately, typescript 1.0 doesn’t allow this. The type of exported values must also be exported from the module. In this case, that defeats the entire point of singletons.
The 1.1 compiler (not officially released yet, but available on GitHub) fixes this.
In the meantime, the workaround is to use declaration merging to export both an interface and an implementation with the same name:
class MyStoreImpl implements MyStore < private _items; getItems() < return this._items; >> interface MyStore < getItems(); >var MyStore:MyStore = new MyStoreImpl(); export = MyStore;
Why is it not possible to export a class instance in, This is the standard way in TS to do a root level export. Is there an easier way of achieving this Yes. export = new Variable. Example: export = new …
Why is it not possible to export a class instance in TypeScript?
Quite by accident, I found this way to export an instance:
class MyClass()<> export default new MyClass();
I had to come up with the following workaround to generate proper javascript code
Not a workaround. This is the standard way in TS to do a root level export.
Is there an easier way of achieving this
Yes. export = new Variable . Example:
Future
For ES modules you should instead use a default export:
export default expo = new Logger("default");
Which will in most cases have the same effect as a root level export.
On https://k94n.com/es6-modules-single-instance-pattern is an additional way of doing this:
export let expo = new Logger("default");
Which has the advatage that it is possible to export several class instances in a *.ts file.
Instantiating a Class in TypeScript, The first problem is that .myOptions does not exist on chartOptions — you want options. You should capitalize all of your types: MyOptions, …
Export a TypeScript class from another file than it has been defined in
So Ryan Cavanaugh from the TypeScript team was kind enough to answer my question over at their GitHub.
It’s actually pretty easy: Just combine both of the approaches I came up with and you’re good to go:
// api.ts import < Foo as MyFoo >from "./lib/foo"; import < Bar as MyBar >from "./lib/bar"; export namespace MyModule < export const Foo = MyFoo; export type Foo = MyFoo; export namespace MySubModule < export const Bar = MyBar; export type Bar = MyBar; >>
EDIT 2020: Now that I have some more years of TypeScript experience, I think I should provide an additional explanation why the code above works. This may be valuable information for new-ish TypeScript developers, because it touches a topic that is not often taught: TypeScript’s separate type scope.
TypeScript basically maintains a type scope parallel to the variable scope of JavaScript. This means that you may define a variable foo and a type foo in the same file. They don’t even need to be compatible:
const foo = 'bar' type foo = number
Now classes in TypeScript are a little bit special. What happens if you define a class Foo is that TypeScript not only creates a variable Foo (containing the class object itself) it also declares a type Foo , representing an instance of that class.
Similarly, when importing a name from another file, both — any defined variable and type under that name — are imported. This means that in the code above, MyFoo holds the Foo class object as well as the Foo class type from foo.ts .
So if we re-export MyFoo from inside the MyModule namespace by writing export const Foo = MyFoo , only the class object is exported (because a const only ever holds a value, not a type). Similarly, if we’d do export type Foo = MyFoo , only the class type would be exported.
So now we’ve come full circle: Because of the independent scopes, it’s valid to export a value and a type under the same name. And in some cases (like this one), it’s not only valid but necessary.
Typescript: Export instance of class that holds state, class MyStore < >// export a single instance export = new MyStore(); Unfortunately, typescript 1.0 doesn’t allow this. The type of exported …
In typescript, how to export the type of a private class without exporting class itself
Why export of type using typeof not working?
export type MyInterface = typeof MyClassPrivateHelper
In this example MyInterface is the type of the constructor function but you’d like to export the type of the instances this constructor can produce.
How do I export type without exposing the private class outside module?
export type MyInterface = InstanceType
InstanceType is described briefly here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html.
Alternatively, I found that the following also works:
type Interface = < [P in keyof T]: T[P] >export interface MyInterface extends Interface <>
The Interface type basically copies all public properties from T , which we then use to declare a new interface.
See https://github.com/Microsoft/TypeScript/issues/471#issuecomment-381842426 for more details.
You should create an interface and export that:
export interface IMyHelper
and then let the Helper implement that:
class MyClassPrivateHelper implements IMyHelper < constructor(private cls: MyClass) < >public someHelperMethod(arg): void < this.cls.someMethod(); >>
The public class will return the interface
export class MyClass < public createHelper(): IMyHelper < return new MyClassPrivateHelper(this); >public someMethod(): void < /**/ >>
From the outside the helper is again referenced by its interface:
const helper: IMyHelper = mycls.createHelper();
The simplest way to do this is the following:
class MyClassPrivateHelper < constructor(private cls: any) < >public someHelperMethod(arg: any): void < this.cls.someMethod(); >> export type Helper = MyClassPrivateHelper;
Calling export type Helper = InstanceType is redundant.
Cannot assign exported class instance in typescript, I have an model store class whose instance would be exported like below: export class CartStore < >export default new CartStore (); Later in my …
Typescript export class instance
Пусть у нас будет в проекте файл devices.ts :
export interface Device < name: string; >export class Phone implements Device < name: string; constructor(n:string)< this.name = n; >> export function call(phone: Phone) : void
Чтобы классы, интерфейсы, функции были видны извне, они определяются с ключевым словом export .
Но мы могли бы и по другому экспортировать все сущности:
interface Device < name: string; >class Phone implements Device < name: string; constructor(n:string)< this.name = n; >> function call(phone: Phone) : void < console.log("Make a call by", phone.name); >export ;
Импорт
Чтобы задействовать модуль в приложении, его надо импортировать с помощью оператора import . Например, импортируем класс Phone и функцию Call из выше определенного модуля devices.ts:
import from "./devices"; let iphone: Phone = new Phone("iPhone X"); call(iphone);
После слова import определяется набор импортируемых типов — класов, интерфейсов, функций, объектов. А после слова from указывается путь к модулю. В данном случае модуль располагается в файле devices.js, который находится в той же папке, поэтому в начале пути ставится точка и далее указывается название файла без расширения. Если бы модуль располагался бы в папке lib, находящеся в текущем каталоге, то название папки также бы включалось в путь к модулю: «./lib/devices».
Псевдонимы
При экспорте и импорте для компонента модуля можно указать псевдоним с помощью оператора as :
Например, установка псевдонима для компонента при импорте:
import from "./devices.js"; let iphone: Phone = new Phone("iPhone X"); makeCall(iphone);
Так, в данном случае для функции call() установлен псевдоним makeCall() , и далее мы обращаемся к функции call() через ее псевдоним makeCall() .
Также псевдоним можно установить при экспорте компонента:
interface Device < name: string; >class Phone implements Device < name: string; constructor(n:string)< this.name = n; >> function call(phone: Phone) : void < console.log("Make a call by", phone.name); >export ;
Затем компонент импортируется через его псевдоним:
import from "./devices.js"; let iphone: Phone = new Phone("iPhone X"); makeCall(iphone);
Импорт всего модуля
Можно импортировать сразу весь модуль:
import * as dev from "./devices.js"; let iphone: dev.Phone = new dev.Phone("iPhone X"); dev.makeCall(iphone);
В данном случае модуль импортируется через псевдоним «dev». И, используя этот псевдоним, мы можем обращаться к расположенным в этом модуле типам.
Экспорт по умолчанию
Параметры экспорта по умолчанию позволяют определить тип, который будет импортироваться из модуля по умолчанию. К примеру, добавим новый модуль smartwatch.ts :
export default class SmartWatch < constructor(private model:string)<>printModel()< console.log(`Model: $`); > >
Ключевое слово default позволяет установить класс SmartWatch в качестве типа по умолчанию. И затем мы можем импортировать его следующим образом:
import SmartWatch from "./smartwatch.js"; let watch: SmartWatch = new SmartWatch("Apple Watch"); watch.printModel();
При этом мы можем установить для экспортируемого по умолчанию компонента другое имя:
import Watch from "./smartwatch.js"; let watch: Watch = new Watch("Apple Watch 2"); watch.printModel();