我可以轻松获得具有多个值的导出默认值:
class Car {...}
class Bus {...}
export default { Car, Bus }
我还可以轻松获得某种类型的默认导出
export default interface Airplane {...}
但是我不能默认导出多种类型
interface Airplane {...}
interface Motorcycle {...}
// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Airplane, Motorcycle }
或者多种类型和值的混合。
class Car {...}
interface Motorcycle {...}
// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Car, Airplane }
我怎样才能实现这个目标?
考虑
export =
语法。
export =
语法指定从模块导出的单个对象。这可以是类、接口、命名空间、函数或枚举。
车辆.ts
namespace Vehicle {
export class Car {
// ...
}
export class Bus {
// ...
}
}
export = Vehicle;
测试1.ts
import Vehicle from './Vehicle';
const car = new Vehicle.Car();
const bus = new Vehicle.Bus();
测试2.ts
import { Bus, Car } from './Vehicle';
const car = new Car();
const bus = new Bus();
参见 https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require
事实上,通过这样导出:
class Car {...}
interface Motorcycle {...}
// 'Airplane' only refers to a type, but is being used as a value here. ts(2693)
export default { Car, Airplane }
您所做的是**导出具有两个属性的默认对象*.*
稍后,在您的代码中,您可以像这样导入它:
// name is as you like, its default import
import transport from transport;
并像这样使用它:
....new transport.Car()
....new transport.Plane()
实际上,您可以通过仅包含命名导出的帮助程序文件来默认导出多种类型和值,然后将该文件中的所有内容导出为默认值。
例如:
// named-exports.ts
export interface Vehicle {...}
export class Car {...}
export class Airplane {...}
// default-export.ts
export * as default from "./named-exports";
您现在可以从
default-exports
导入所有内容并引用类型和值。
例如:
// usage-example.ts
import Transport from "./default-export";
let car: Transport.Vehicle = new Car();