Skip to content

TSC Strict mode error TS2722: Cannot invoke an object which is possibly 'undefined'. #31609

@jameshmread

Description

@jameshmread

TypeScript Version: 2.7.2
Have also reproduced with typescript@next (3.5.0-dev.20190525).

Application insights version: 1.0.20

Search Terms:
error TS2722 cannot invoke an object which is possibly 'undefined'.
typescript error
Application insights

Code

I am moving our codebase, incrementally to use strict null checks using a new tsconfig.strict.json below.

{
    "extends": "./tsconfig.app.json",
    "compilerOptions": {
        "noEmit": true,
        "strictNullChecks": true
    },
    "include": [
        "app/menus/",
        "app/layout/",
        "app/core/"
    ],
    "exclude": [
        "**/*.module.ts",
        "**/*.spec.ts"
    ]
  }
  

Here are the relevant parts of the file in question ApplicationInsights.ts...

import { AppInsights as appInsights } from 'applicationinsights-js';
...
    constructor(private readonly appConfig: AppConfigProvider) {
            if (appInsights && !appInsights.config && this.config) {
                appInsights.downloadAndSetup(this.config);
            }
    }

Note: I have also tried being explicit with a constant as seen below and receive the same error...

   constructor(private readonly appConfig: AppConfigProvider) {
        const ai = appInsights;
        if (ai !== void 0) {
            if (!ai.config && this.config) {
                ai.downloadAndSetup(this.config);
            }
        }
    }

Expected behavior:
No error is thrown by tsc compiler.
Actual behavior:
src/application-insights/ApplicationInsights.ts(25,17): error TS2722: Cannot invoke an object which is possibly 'undefined'.

i.e. it believes that appInsights (or ai ) is undefined even inside a check to prevent it from being undefined.

Thanks in advance.

Related Issues:
Related Issues: #22385 (dupe of 10530) #10530

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions