Search code examples
node.jstypescriptexpressundefineddotenv

Cannot resolve TS2532: Object is possibly 'undefined'


I have this code. WebStorm shows, that there is error TS2532: Object is possibly 'undefined'. I have installed dotenv and @types/dotenv but still have this error. How to I fix it?

Here is code:

import jwt from "jsonwebtoken";
import fs from 'fs';
import path from 'path';

import { JwtPayload } from "../interfaces/jwt";

const privateKey = fs.readFileSync(path.resolve(__dirname + "../../../keys/private.pem"));
const publicKey = fs.readFileSync(path.resolve(__dirname + "../../../keys/public.pem"));

export = {
  sign: (payload: JwtPayload) => {
    try {
      return jwt.sign(
        payload,
        {
          key: privateKey,
          passphrase: process.env.JWT_PASSPHRASE.toString()
        },
        {
          algorithm: "RS256",
          expiresIn: "30m"
        }
      )
    } catch (e) {
      //
    }
  },

Also want to say, that I have the same version on dotenv and @types/dotenv - ^8.2.0. I was trying to add this module like this, but it doesn't work:

import * as dotenv from 'dotenv';
dotenv.config()

Solution

  • I solved this problem by setting strictNullChecks to false in tsconfig.json:

    "strictNullChecks": false,