Working with this interface:
export interface NPMPackage {
name: string;
description: string;
'dist-tags': {
[tag: string]: string;
};
versions: {
[version: string]: {
name: string;
version: string;
dependencies?: {
[packageName: string]: string;
};
};
};
}
This is my code snippet:
let dependencies = npmPackage.versions[version].dependencies;
dependencies = Object.entries(dependencies).map( ([name, version]) => ({
name,
version: version.replace(/[^\w\s]/gi, ''),
}));
The above code returns the following errors:
Error message: Type '{ name: string; version: string; }[]' is not assignable to type '{ [packageName: string]: string; }'. Index signature is missing in type '{ name: string; version: string; }[]'.
No overload matches this call. Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike): [string, string][]', gave the following error. Argument of type '{ [packageName: string]: string; } | undefined' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike'. Type 'undefined' is not assignable to type '{ [s: string]: string; } | ArrayLike'. Overload 2 of 2, '(o: {}): [string, any][]', gave the following error. Argument of type '{ [packageName: string]: string; } | undefined' is not assignable to parameter of type '{}'. Type 'undefined' is not assignable to type '{}'.
It works without the dependencies
function. If I use dependencies:any
and modify the versions
variable without any transformations, like so:
let dependencies = npmPackage.versions[version].dependencies;
// Clean it up a bit.
dependencies = Object.entries(dependencies).map( ([name, version]) => ({
name,
version,
}));
it works fine.
My objective is to rearrange the object structure by adding the dependencies method. The new structure of the objects is passed to the new variable dependencies
. What is the correct TypeScript approach for such cases? Is it considered good practice when type hinting?
The API provides data as described, but I want to send it with a different structure for the React frontend application.
One thing that perplexes me is that the variable is a string according to the interface. Why doesn't it work then?