You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在遵循ES2015模块规范下保留TypeScript声明合并的使用效果?

Fixing the TypeScript Namespace Lint Error While Keeping Your Original API

Got it, let's solve this while preserving exactly how you use Product, Product.Seller, and Product.Price—no weird Product.Product or Product.default workarounds needed. The key is to use pure ES module patterns and attach your nested classes as static properties to the main Product class.

Refactored product.ts Code

// First define your nested classes (we'll attach them to Product later)
class Seller {
  constructor(public name: string, public country: string) {}
}

class Price {
  constructor(public currency: string, public value: number) {}
}

// Define the main Product class, then attach Seller/Price as static properties
export default class Product {
  constructor(public name: string, public seller: Seller, public price: Price) {}

  // Make Seller and Price accessible via Product.Seller/Product.Price
  static Seller = Seller;
  static Price = Price;
}

Optional: Lock Down Encapsulation

If you don't want Seller and Price to be usable outside of the Product context (i.e., prevent someone from importing them directly), just leave them unexported like above. They'll only be accessible via Product.Seller and Product.Price, matching your original encapsulation intent perfectly.

Usage in Other Files (Exact Same as Before!)

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);

Why This Works

  • No more lint errors: We're using standard ES modules, no TypeScript-specific namespaces involved.
  • API stays identical: You still create main product instances with new Product(...), access nested classes with Product.Seller, and use types like Product.Price for type checking—zero changes to your existing code.
  • TypeScript is fully happy: The type system correctly recognizes Product.Seller and Product.Price as both constructors and types, just like your original declaration merge setup.

内容的提问来源于stack exchange,提问作者CLDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:57:32