我有一个类和一个名称空间,其声明合并定义如下:
// product.ts
export class Product {
constructor(public name: string, public seller: Product.Seller, public price: Product.Price) {}
}
export namespace Product {
export class Seller {
constructor(public name: string, public country: string) {}
}
export class Price {
constructor(public currency: string, public value: number) {}
}
}
export default Product
我可以将它导入另一个文件并使用 Product、Product.Seller 和 Product.Price 来创建新对象以及进行类型检查:
// index.js
import Product from './product'
function discountPrice(price: Product.Price, discount: number): Product.Price {
return new Product.Price(price.currency, price.value * discount)
}
const seller = new Product.Seller('John', 'US')
const price = new Product.Price('USD', 749.9)
const priceWithDiscount = discountPrice(price, 0.7)
const product = new Product('Dell Laptop', seller, priceWithDiscount)
在我对文件进行 lint 之前,一切都运行良好。我收到错误“ES2015 模块语法优于自定义 TypeScript 模块和命名空间”。
该错误很直观,我可以通过删除命名空间并将 product.ts 作为命名模块导入来轻松摆脱它:
// product.ts
export class Product {
constructor(public name: string, public seller: Seller, public price: Price) {}
}
export class Seller {
constructor(public name: string, public country: string) {}
}
export class Price {
constructor(public currency: string, public value: number) {}
}
// index.js
import * as Product from './product'
问题是,现在 Product 类本身位于 Product 模块中,我必须将其称为 Product.Product:
const product = new Product.Product('Laptop', seller, priceWithDiscount)
我再次尝试匿名导出默认的 Product 类,但我仍然得到一个错误,最后我不得不将它称为 Product.default:
// product.ts
export default class {
constructor(public name: string, public seller: Seller, public price: Price) {}
}
...
// index.ts
const product = new Product.default('Laptop', seller, priceWithDiscount)
是否可以在遵守无命名空间规则的同时保留原始设计的结果?任何帮助将不胜感激!