问题
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