Maxime Dupré
Maxime Dupré

Reputation: 5747

How to have an "export default" with multiple types and values in a TypeScript module?

I can easily have an export default with multiple values:

class Car {...}
class Bus {...}

export default { Car, Bus }

I can also easily have an export default of a type

export default interface Airplane {...}

But I can't have a default export of multiple types

interface Airplane {...}
interface Motorcycle {...}

// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Airplane, Motorcycle }

Or of a mix of multiple types and values.

class Car {...}
interface Motorcycle {...}

// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Car, Airplane }

How can I achieve this?

Upvotes: 9

Views: 29820

Answers (3)

Igor Stojadinović
Igor Stojadinović

Reputation: 76

You actually can have a default export of multiple types and values by having a helper file with named exports only and then exporting everything from that file as default.

For example:

// named-exports.ts
export interface Vehicle {...}
export class Car {...}
export class Airplane {...}
// default-export.ts
export * as default from "./named-exports";

You can now import everything from default-exports and refer both to types and values.

For example:

// usage-example.ts
import Transport from "./default-export";
let car: Transport.Vehicle = new Car();

Upvotes: 0

SilenceDis
SilenceDis

Reputation: 91

Consider export = syntax.

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.


Vehicle.ts

namespace Vehicle {
    export class Car {
        // ...
    }

    export class Bus {
        // ...
    }
}

export = Vehicle;

Test1.ts

import Vehicle from './Vehicle';

const car = new Vehicle.Car();
const bus = new Vehicle.Bus();

Test2.ts

import { Bus, Car } from './Vehicle';

const car = new Car();
const bus = new Bus();

See https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require

Upvotes: 9

Theo Itzaris
Theo Itzaris

Reputation: 4681

In fact, by exporting like so:

class Car {...}
interface Motorcycle {...}

// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Car, Airplane }

What you do is to **export a default object with two properties*.*

Later, in your code, you can import it like so:

// name is as you like, its default import
import transport from transport;

and use it like so:

....new transport.Car()
....new transport.Plane()

Upvotes: 2

Related Questions