This code gives me "Type 'string' is not assignable to type 'never'" where the comment is made.
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';
});
If I change the code to this:
serviceInfo[e as string] = 'something';
Then it works. But I have no idea why it doesn't work. Can anyone explain why it says type never?
EDIT:
Alex Kolarski made a right call of me trying to assign .env variables (which types I changed).
You can do this (which works and is correct way):
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 is "essentially" this:
serviceInfo[e] = process.env[e];
Except this doesn't work.
If you don't need anything else but to assign values you are OK with the 'as string' hack. But if you need to do other stuff like changing or checking types of the variables, you should use the correct way. Because then the intellisense works and TS is happy.