Argument of type 'string | string[] | ParsedQs | ParsedQs[] | undefined' is not assignable to parameter of type 'string'

喜欢而已 提交于 2021-01-29 20:13:24

问题


This Error keeps bugging me, a (Type 'string[]' is not assignable to type 'string') error in this code

export const generateLabelFile = functions.https.onRequest(
  async (request, response) => {
    const dataset = request.query['dataset'];
    if (!dataset) {
      response.status(404).json({ error: 'Dataset not found' });
    }
    try {
      const labelsFile = await generateLabel(dataset);
                                               ^^^ ERROR ABOVE
      response.json({ success: `File uploaded to ${labelsFile}` });
    } catch (err) {
      response.status(500).json({ error: err.toString() });
    }
  }
);


async function generateLabel(dataset: string): Promise<String> {
  const storage = new Storage({ projectId: PROJECT_ID });
  const prefix = `datasets/${dataset}`;

  // get all images in the dataset
  const [files] = await storage.bucket(AUTOML_BUCKET).getFiles({ prefix });

  const csvRows = files
    .map(file => getMetadata(file.name))
    .filter((metadata): metadata is ImageMetadata => metadata !== null)
    .map(({ label, fullPath }) => `gs://${AUTOML_BUCKET}/${fullPath},${label}`);

  console.log('Total rows in labels.csv:', csvRows.length);

  // No videos found, abort
  if (csvRows.length === 0) {
    throw new Error(`No videos found`);
  }


I'm really confused on how I can reslove this error.


回答1:


The type for request.query is QueryString.ParsedQs which comes from the qs package. This package is able to read and parse complicated query vars and not just "key=value" pairs. A user could use a URL query like ?dataset[]=first&dataset[]=second, which would be interpreted as an array ["first", "second"].

It is up to you how your program should deal with these inputs. Do you want to handle them, or throw errors? You could check if dataset is an array of strings and call generateLabel on each element. But the simplest solution is to make sure that dataset is a string and return an error otherwise.

Note that you need some sort of return or else before going into the try/catch block so that you don't call generateLabel with non-strings.

export const generateLabelFile = functions.https.onRequest(
  async (request, response) => {
    const dataset = request.query['dataset'];
    if (!dataset) {
      response.status(404).json({ error: 'Dataset not found' });
      return;
    }
    if ( typeof dataset !== "string" ) {
      response.status(500).json({ error: 'Invalid dataset' });
      return;
    }
    try {
      const labelsFile = await generateLabel(dataset);
      response.json({ success: `File uploaded to ${labelsFile}` });
    } catch (err) {
      response.status(500).json({ error: err.toString() });
    }
  }
);

Another way to handle this, since you are already using a try/catch around generateLabel, is to validate the dataset within the generateLabel function. You would allow the function to accept dataset: any, but throw an Error if dataset is anything other than string.



来源:https://stackoverflow.com/questions/65739067/argument-of-type-string-string-parsedqs-parsedqs-undefined-is-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!