typescript narrow type on throw
I have this code here
but it doesn't narrow salt rounds type for export.
I tried this but it also doesn't work. Do i have to reassign a value or is there another way
22 Replies
ignore the asseerts param is string. I'm just trying to get something working for now
process.env.SALT_ROUNDS
<-- isn't the type of this set to any
by default?
if you want a string, just try something like this:
--------
maybe something like this could work too - I DO NOT KNOW IF THIS WORKS OR NOT!!!!:
the as syntax won't work. That jus works like an alias similar to the import statement counterpart
yeah I guess I'll have to do this one. Annoying but works
i expected it to do not work, but wasn't sure
it is annoying
you can use jsdoc
just do
/** @type {string|undefined} */
that should workthat's actually already the type of env vars on process.env

then you have to do the first one, to make sure it is a string
yeah, that's not a good idea
i don't think that the number constructor accepts undefined
it gives out NaN which throws error when doing !SALT_ROUNDS
tho yes I should do 0 with your ??
you should do
'0'
how about this
it's missing the types for the parameters in the jsdoc, even if it is redundant
why add them if they are redundant though? jsDoc with typescript mainly seems to be for doc intellisense while typescript handles the types
🤔
it was the first thing i noticed
but why are you asserting the environment var by throwing an error?
I want the whole app to crash if environment var is not present/undefined. It should not work at all
the number one will fail if it converts to
NaN
ah dammit true
maybe i should remove the 0 and "" condition since !envVar takes care of that but I like to be explicit
this should take care of everything and is more readable
What exactly are you trying to do?
well in the beginning I was trying to assert that env vars are of string type
by throwing errors if they were undefined
Let me rephrase, why are you trying to do that?
What is the end goal
the app should not work if the env variable is undefined but throwing errors will not narrow the type.
so i had to assign empty string or 0 (in case of salt rounds) to narrow the type to string or number. Then the above function checks if the env var is empty string 0, NaN or falsy then throws
throwing errors is simply for my convenience as it will inform me if i forgot to set an environment variable
what you posted should work, but in general it's better to check the validity of the inputs where they are used, that way you can provide more contextual error message. 'cause right now you would get something like
Error: SALT_ROUND enviroment varibale not provided
but you would not know what it does, why it's needed or even what the value should beI do have an env.example file to explain the purpose of all environment variables.
I guess I'll do it where it should be