MonkBen
MonkBen

Reputation: 644

How to expose types returned by API in typescript

I am creating a typescript library that can call web services and return data. It provides an API to call the different web services. Each API call returns data of a certain type. In my main module, I export the API.

I can't figure out the best way to expose the types returned by the API. Given that the types have sub-types and so on, there at least 100 types. For readability and abstraction I put them in multiple files.

I thought I could put all the types in the same namespace and then just expose the namespace. I couldn't figure out how to export a single namespace though in typescript. This lead me to believe there is a different way to tackle this problem but I'm not sure what.

Example:

// api.ts
export function getData(): IData;
export function getData2(): IData2;
// IData1.ts
export interface IData1 {
    subData: ISubData1;
}

export interface ISubData1: {
    value: string;
}
// IData2.ts
export interface IData2 {
    subData: ISubData2;
}

export interface ISubData2: {
    subSubData: ISubSubData2;
}

export interface ISubSubData2 {
    value: string;
}
// index.ts
import * as api from "./api";
export {api};

// What is the best way to export the type interfaces so that the consumer of this library has type checking?

Upvotes: 1

Views: 1711

Answers (1)

user12251171
user12251171

Reputation:

You can just export everything from each file in your index.ts, like this:

export * from './api.ts';
export * from './IData1.ts';
export * from './IData2.ts';

If you plan on distributing this through npm, be sure to generate and include your declaration files (.d.ts) in the distribution. As well as set the types field in your package.json. More on that here.

Also, you have expose in your api.ts snippet here, that should be export I'm assuming. :P

Upvotes: 2

Related Questions