Skip to content

Typescript: _comment does not accept string[] #202

@threedot14

Description

@threedot14

Reproducing steps

Consider the following

  const input = {
    _declaration: { _attributes: { version: '1.0', encoding: 'utf-8' } },
    _comment: [
      'Hello1',
      'Hello2'
    ],
    data: {some: 'value'}
  }

  const output= convert.js2xml(xmlData, { compact: true, spaces: 2 })

This code works as a JS module.
This is also explicitly tested in https://github.com/nashwaan/xml-js/blob/f0376f265c4f299100fb4766828ebf066a0edeec/test/test-items.js#L42C30-L42C30

Expected Outcome

This code should also work as a Typescript block as well.

Actual Outcome

TS compiler says _comment does not accept string[]

TS2345: Argument of type '{ _declaration: { _attributes: { version: string; encoding: string; }; }; _comment: string[]; data: { some: string; }; }' is not assignable to parameter of type 'Element | ElementCompact'.
  Type '{ _declaration: { _attributes: { version: string; encoding: string; }; }; _comment: string[]; data: { some: string; }; }' is not assignable to type 'ElementCompact'.
    Types of property '_comment' are incompatible.
      Type 'string[]' is not assignable to type 'string'.

Because,

_comment?: string
defines _comment as string only.

Proposed solution

can we make the type definition this intead?

_comment?: string | string[]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions