Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: after the transpilation, wrong retun type

Why my index.ts

export const isNullOrUndefined = (value: any): value is null | undefined => {
  return value === null || value === undefined;
};

is transpiled into index.d.ts (only value is null)

export declare const isNullOrUndefined: (value: any) => value is null;

instead of (value is null | undefined)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export declare const isNullOrUndefined: (value: any) => value is null | undefined;

this is the tsconfig file on typescript 4.9.5

{
  "compilerOptions": {
    "incremental": false,
    "target": "es2019",
    "outDir": "build",
    "rootDir": "src",
    "moduleResolution": "node",
    "module": "commonjs",
    "declaration": true,
    "inlineSourceMap": false,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "removeComments": false,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "traceResolution": false,
    "listEmittedFiles": false,
    "listFiles": false,
    "pretty": true,
    "lib": ["es2019", "dom"],
    "types": ["node"],
    "typeRoots": ["node_modules/@types", "src/types"]
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules/**"],
  "compileOnSave": false
}

>Solution :

It’s because you don’t have strictNullChecks enabled. From the option’s documentation:

When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.

When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

Add at least:

"strictNullChecks": true,

to your tsconfig.json (although I’d recommend all of the strict flags, via "strict": true).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading