Dynamic import not inferred fails when `strictNullChecks: true`

Viewed 42

Edit: new info, this works if I set strictNullChecks: false. So I presume this is to do with guaranteeing that the import actually returns something. The question is therefore how can I allow for that in my type definitions (assuming that this is an API and users should be allowed to define the import how they wish).

This is a strange one. I'm trying to infer the return type of a dynamic import, and am extracting a returned property's key.

This works on StackBlitz here: https://stackblitz.com/edit/typescript-b98poh?file=index.ts

But doesn't work locally: enter image description here

As you can see from my screenshot, I'm trying to define this module as:

factory: () => import('./shared/data/data.module').then(mod => mod.createDataModule)

But type inference doesn't work if I do that. It only works if I use:

factory: async () => (await import('./shared/data/data.module')).createDataModule,

However, you can see from the stackblitz that this does indeed work correctly. The import paths are different, but the contents are exactly the same:

export function createDataModule() {
  return {
    services: {
      createResource: () => {},
    },
  };
}

So what is it about my setup that is disallowing the direct return of the import?

Here's my TSConfig:

    "compilerOptions": {
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "importsNotUsedAsValues": "error",
    "outDir": "../../dist/out-tsc",
    "module": "esnext",
    "preserveValueImports": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "types": ["node", "@cloudflare/workers-types"]
  },

which extends:

    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "downlevelIteration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2018",
    "module": "esnext",
    "lib": ["es2019", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",

TS version is 4.7.4

0 Answers
Related