I'm writing a library with TypeScript to be used by both js and ts projects. I compile it and upload both the .js and .d.ts files to npm, my main.ts exports the following:
interface MyInterface{
// ...
}
class MyClass{
public myMethod(): MyInterface { /* code */ }
}
export = new MyClass();
A js project can then install and import the library directly:
const myLib=require('my-lib');
myLib.myMethod(); // OK
A typescript project can also import the library:
import * as myLib from 'my-class';
myLib.myMethod(); // OK
However, I want to also export MyInterface
for typescript projects so I can do the following in a project importing my library:
import {MyInterface} from 'my-lib';
function anotherFunction(arg: MyInterface){
}
I have no idea how should I export things in my main.ts so I can achieve something like this while keeping the same support for javascript-based projects.
Just export both interface and class,
// my-lib
export interface MyInterface{
// ...
}
export class MyClassStatic{
// if your method not dealing with any context(this), you can decalre the method as 'static'
public static myMethod(): MyInterface { /* code */ }
}
export class MyClass{
public myMethod(): MyInterface { /* code */ }
}
In code,
import * as myLib from 'my-lib';
// accessing static method
myLib.MyClassStatic.myMethod();
// accessing class members
const myClass = new myLib.MyClass();
myClass.myMethod();
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.