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

子类构造函数super需前置时,如何对Transform入参做运行时类型检查

Validate to Parameter Before super() in TypeScript Constructor

Got it, let's work through this problem. You need to make sure objectMode is always true for your XMLParser class, plus add custom validation for the to parameter—but TypeScript's rule that super() must be the first statement in the constructor is blocking your initial approach.

Here's a clean, TypeScript-compliant workaround using an immediately-invoked function expression (IIFE). Since super() accepts an expression as its argument, we can wrap our validation and parameter merging logic inside an IIFE that runs right when we call super():

import { Transform, TransformOptions } from 'stream'; // Assuming Node.js streams context

type XMLParserOpts = { /* Define your options type here */ };

export class XMLParser extends Transform {
  constructor(opts?: XMLParserOpts, to?: TransformOptions) {
    super((() => {
      // Custom validation for the `to` parameter
      if (to !== undefined) {
        if (typeof to !== 'object' || to === null) {
          throw new Error('Invalid "to" parameter: must be a plain object (or undefined)');
        }
      }

      // Merge parameters and force objectMode to true
      return Object.assign({}, to || {}, { objectMode: true });
    })());
  }
}

Key Details:

  • Why the IIFE? TypeScript requires super() to be the first executable statement in the constructor, but it allows expressions as arguments to super(). The IIFE lets us run validation logic before the config object is passed to super(), while still keeping super() as the first statement.
  • Improved validation check: Your original check missed a edge case—null has a typeof of 'object', but it's not a valid TransformOptions value. The updated check ensures to is either undefined, a non-null object, or throws your custom error.
  • Guaranteed objectMode: By placing { objectMode: true } last in Object.assign(), we override any existing objectMode value the user might have passed, ensuring it's always set to true.

This approach keeps your custom error messaging intact, follows TypeScript's rules, and ensures your class behaves consistently.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:42:32