【问题标题】:Import namespaced class specifically专门导入命名空间类
【发布时间】:2016-12-03 03:41:47
【问题描述】:

我有一个这样设置的命名空间:

export namespace Entities {

    export class Car { }

    export class Motorbike { }

}

然后我在另一个类中导入CarMotorbike。但是,我无法简洁地导入它们。如果我尝试像这样导入它们:

import { Entities.Car as Car, Entities.Motorbike as Motorbike } from "./somefile.ts";

我收到此错误(在Entities 之后的.):

',' 预期。

我可以做到:

// import whole namespace
import { Entities } from "./somefile.ts";

// use the type directly:
let vehicle: Entities.Car;

但理想情况下,我可以在不手动导入命名空间的情况下导入它们。这可能吗?

【问题讨论】:

    标签: typescript syntax tsc typescript-typings


    【解决方案1】:

    我不明白你为什么要在这种情况下使用命名空间。你有几个选择:

    • 在全局声明文件中定义您的类。然后,您可以直接在程序中使用您的类型,而无需导入它们。

      // index.d.ts
      declare class Car {
        someProperty: any
      }
      
      // app.ts
      let theCar: Car
      theCar.someProperty
      
    • 在模块声明文件中定义您的类。然后,您必须导入要使用的特定类型。

      // index.d.ts
      export class Car {
        someProperty: any
      }
      
      // app.ts
      import { Car } from './index'
      let theCar: Car
      theCar.someProperty
      

    【讨论】:

      猜你喜欢
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多