Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

typescript - How can I add a type from an npm package into a `d.ts` file declared namespace?

I have this TYPES.d.ts file where I declare a TYPES namespace

declare namespace TYPES {

  type TYPE_A = XXX;
  type TYPE_B = YYY;

}

And then I use is like: const someFunc = (param: TYPES.TYPE_A): void => { ... };

It works fine.

But now I'd like to add a type on the TYPES namespace that is a return type from a type that exists on an NPM package.

TYPES.d.ts

import type { SomeType } from "some-npm-package";

declare namespace TYPES {
  type SOME_TYPE = ReturnType<typeof SomeType>;
}

But this "breaks" the d.ts file, because it seems Typescript considers it to be a module, instead of a definition file.

How can I achieve that and still be able to access it through my namespace?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just found a way of doing it:

TYPES.d.ts

declare namespace TYPES {
  type SOME_TYPE = ReturnType<typeof import("some-npm-package").SomeType>;
  type OTHER_TYPE = typeof import("some-npm-package").SomeType
  type FOO_TYPE = typeof import("./someFile").FooType  // ALSO WORKS WITH SRC FILES
}

This way you avoid the top-level import that "breaks" the d.ts file declared namespace.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...