I encountered an issue with this code where it's giving me an error message "Type 'string' is not assignable to type 'never'" at the specified comment.
type serviceInfoType = {
PORT: number;
HOST: string;
MS_NAME: string;
MS_KEY: string;
};
type serviceInfoParametersType = keyof serviceInfoType;
let serviceInfo = {} as serviceInfoType;
let serviceInfoParameters: Array<serviceInfoParametersType> = [
"PORT",
"HOST",
"MS_NAME",
"MS_KEY",
];
serviceInfoParameters.forEach((e) => {
// Type 'string' is not assignable to type 'never'
serviceInfo[e] = 'something';
});
After making a small adjustment to the code as shown below:
serviceInfo[e as string] = 'something';
The error is resolved. However, I'm confused as to why it initially showed the 'type never' error.
UPDATE:
After a helpful suggestion from Alex Kolarski, I realized that the issue might be related to assigning .env variables (with modified types).
An alternative correct approach to handle this issue is:
if (e === "PORT") serviceInfo[e] = process.env[e];
else if (e === "MICROSERVICE_NAME") serviceInfo[e] = process.env[e];
else serviceInfo[e] = process.env[e];
Which can be simplified to:
serviceInfo[e] = process.env[e];
However, the simplified version does not seem to work in this case.
If your main aim is just to assign values, the 'as string' workaround should suffice. But for more complex operations involving variable types, it's advisable to follow the correct approach to ensure compatibility with TypeScript and intellisense functionalities.