In TypeScript, interface defines string, however returned type is string[]. How to properly access returned array?

58 Views Asked by At

I have observed a strange behavior of my node application using GraphicsMagick.

I would like to identify the number of pages in a pdf file. Therefore, I use "identify" which returns an object of type gm.ImageInfo. Then I "destructure" the returned object to obtain an array of strings that describe the format of my input file. The length should be the number of pages (which it actually is).

What strikes me is that Format inside the interface gm.ImageInfo is defined as string, however "identify" returns an array of strings (in case the input file consists of multiple pages). Still, I cannot formally define my "Format" variable as "string[]" because TypeScript tells me that a string cannot be assigned to an array of strings (which is obviously correct). How can I solve that conflict an obtain the actual array of strings returned by "identify"?

Here is the relevant extract of my code:

This works but I do not formally get an array of strings:

import gm from 'gm';

gm('test.pdf').identify((err: any, value: gm.ImageInfo) => {
  const { Format, ...rest }: gm.ImageInfo = value;
  console.log(Format);
  console.log(Format.length);
  if (err) {
    console.log('err');
  }
});

This does not work since TypeScript complains:

import gm from 'gm';

gm('test.pdf').identify((err: any, value: gm.ImageInfo) => {
  const { Format, ...rest }: { Format: string[] } = value;
  console.log(Format);
  console.log(Format.length);
  if (err) {
    console.log('err');
  }
});

Format typically contains something like this (for example if the input pdf contains 7 pages):

[
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)',
  'PDF (Portable Document Format)'
]

This looks very much like an array. Format.length is 7 (= the number of pages). However, the type of Format is not string[]. How can I convert Format to a string[] to obtain an actual array?

0

There are 0 best solutions below