Issue
I'm trying to write a Type Guard, such that TypeScript doesn't throw an error anymore on the last line where I try to load data based on a certain key. Somehow TypeScript still things that the environment variable is a string rather than a known key of the object. Since it now throws: No index signature with a parameter of type 'string' was found on type....
Am I missing some edge case here where the environment variable could still be undefined as a key?
import JsonData from '../data/data.json'
const doesKeyExist: (
input: string | undefined
) => boolean = (input) =>
input && JsonData.hasOwnProperty(input)
if (!doesKeyExist(process.env.SOME_VARIABLE))
throw Error('Environment Variable not declared!')
const data = JsonData[process.env.NEXT_PUBLIC_TENANT_ID]
Solution
This seems to do the trick:
import JsonData from '../data/data.json'
function doesKeyExist(
input: string | undefined
): input is keyof typeof CategoriesData {
return !!(input && CategoriesData.hasOwnProperty(input))
}
if (!doesKeyExist(process.env.SOME_VARIABLE))
throw Error('Environment Variable not declared, or key does not exist in config file!')
const data = JsonData[process.env.NEXT_PUBLIC_TENANT_ID]
Answered By - maus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.