打字稿:环境变量类型保护作为 JSON 对象的键
Typescript: Type Guard for environment variable as key of JSON object
我正在尝试编写一个 Type Guard,这样 TypeScript 就不会再在我尝试基于某个键加载数据的最后一行抛出错误。不知何故,TypeScript 仍然认为环境变量是 string
而不是对象的已知键。因为它现在抛出:No index signature with a parameter of type 'string' was found on type...
.
我是否遗漏了环境变量仍然可以 undefined
作为键的一些边缘情况?
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]
这似乎可以解决问题:
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]
我正在尝试编写一个 Type Guard,这样 TypeScript 就不会再在我尝试基于某个键加载数据的最后一行抛出错误。不知何故,TypeScript 仍然认为环境变量是 string
而不是对象的已知键。因为它现在抛出:No index signature with a parameter of type 'string' was found on type...
.
我是否遗漏了环境变量仍然可以 undefined
作为键的一些边缘情况?
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]
这似乎可以解决问题:
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]