子类构造函数super需前置时,如何对Transform入参做运行时类型检查
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 tosuper(). The IIFE lets us run validation logic before the config object is passed tosuper(), while still keepingsuper()as the first statement. - Improved validation check: Your original check missed a edge case—
nullhas atypeofof'object', but it's not a validTransformOptionsvalue. The updated check ensurestois eitherundefined, a non-null object, or throws your custom error. - Guaranteed
objectMode: By placing{ objectMode: true }last inObject.assign(), we override any existingobjectModevalue the user might have passed, ensuring it's always set totrue.
This approach keeps your custom error messaging intact, follows TypeScript's rules, and ensures your class behaves consistently.
内容的提问来源于stack exchange,提问作者Alexander Mills

