#Preventing type imports from being rewritten as dynamic imports

3 messages · Page 1 of 1 (latest)

calm perch
#

Hi, I am trying to find a way for my built code using tsc to not transpile imports to dynamic imports because those won't resolve:

Example:

import type {
  RestContext,
} from 'msw'

const buildObject = () => {
  type ContextWithInput = RestContext & { input: () => void }
  return {} as unknown as ContextWithInput
}

when this file is built this is how the import is done:

// ...d.ts
declare const buildObject: () => import("msw/lib/glossary-de6278a9").D & {
        cookie: (name: string, value: string, options?: import("cookie").CookieSerializeOptions | undefined) => import("msw/lib/glossary-de6278a9").R<any, any>;
        text: <BodyType extends string>(body: BodyType) => import("msw/lib/glossary-de6278a9").R<BodyType, any>;
        body: <BodyType_1 extends string | Blob | BufferSource | FormData | ReadableStream<any>>(value: BodyType_1) => import("msw/lib/glossary-de6278a9").R<BodyType_1, any>;
        json: <BodyTypeJSON>(body: BodyTypeJSON) => import("msw/lib/glossary-de6278a9").R<BodyTypeJSON, any>;
        xml: <BodyType_2 extends string>(body: BodyType_2) => import("msw/lib/glossary-de6278a9").R<BodyType_2, any>;
    } & {
        input: () => void;
    }

Is there a way to either keep the import as non dynamic in the .d.ts file import { RestContext } from 'msw' or have the import() statement be import("msw").RestContext

Cheers!

woven shard
#

i'm not sure of the correct terminology but i wouldn't call import("msw/lib/glossary-de6278a9").D in type position a "dynamic import". it's still static. i think that's just the way TS names unnameable types

if you move type ContextWithInput = RestContext & { input: () => void } outside of your function body (and perhaps export it) does the generated .d.ts change? i suspect it will, but can't easily test for myself right now

calm perch
#

You're right dynamic import is the right term. I simplified my test case for the purpose of this post, but I need to have a type defined in the function since it actually relies on generics of this function.

If I try to extract the type with a simple case like the post above it does work, however with a type that depends on a generic it always transpile to the import() statement.