What is the best way to export a default object containing imported types in TypeScript?

I am currently working on creating ambient type definitions for a JavaScript utility package (similar to Lodash). I want users to be able to import modules in the following ways:

// For TypeScript or Babel

import myutils from 'myutils' // myutils = { a: [Function], b: [Function] }
import { a } from 'myutils'   // a: Function
import a from 'myutils/a'     // a: Function

// For JavaScript

const myutils = require('myutils') // myutils = { a: [Function], b: [Function] }
const { a } = require('myutils')   // a: Function
const a = require('myutils/a')     // a: Function

The package structure is as follows:

// a.js
module.exports = () => 'a'
// b.js
module.exports = () => 'b'
// index.js
module.exports = { a: require('./a'), b: require('./b') }

However, I am facing difficulties in writing proper TypeScript ambient definitions for these modules. This is what I have tried so far:

// a.d.ts
export default function a(): string
// b.d.ts
export default function b(): string
// index.d.ts
export { default as a } from './a'
export { default as b } from './b'

export default ...what?

I also attempted the following without success:

// index.d.ts
import a from './a'
import b from './b'

export { a, b }

// Member 'a' implicitly has an 'any' type, but a better type may be inferred from usage.ts(7045)
declare const _default: { a, b }

export default _default

Any insights would be greatly appreciated!

Answer №1

The issue arises from your usage of the identifiers a and b as types in the following code snippet:

declare const _default: { a, b }

This error can be resolved by using typeof a instead:

declare const _default: {
    a: typeof a,
    b: typeof b
}

Access the Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error TS2322: The specified type Login cannot be assigned to the given type

I've been facing an issue while working on my app in react native. The error message I keep encountering is as follows: TS2322: Type 'typeof Login' is not assignable to type ScreenComponentType<ParamListBase, "Login"> | undefined Type ...

Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface: var js ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...

Converting an existing array into a TypeScript string literal type: A step-by-step guide

Converting TypeScript Arrays to String Literal Types delves into the creation of a string literal type from an array. The question raised is whether it's feasible to derive a string literal from an existing array. Using the same example: const furnit ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

How is it possible for the output to be a string array when the variable was declared as a number in TypeScript?

Snippet: function sampleFunction(sample:string|number|string[]) { if(typeof sample == "string") { console.log("Sample is String " + sample); } else if(typeof sample == "number") { console.log("Sample is Number " + sampl ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

Next.js is displaying an error message indicating that the page cannot be properly

Building a Development Environment next.js Typescript Styled-components Steps taken to set up next.js environment yarn create next-app yarn add --dev typescript @types/react @types/node yarn add styled-components yarn add -D @types/styled-c ...

Ways to return bsDateRangePicker to its default value

I'm currently working on creating reactive forms using Angular 9 and integrating ngx-bootstrap. One issue I am facing is with the daterangepicker functionality. Whenever I utilize the form.reset() function, it clears the input field entirely instead o ...

Break down the provided Array type into distinct new types

If we have a specific type defined as: type Tuple = [name: string, age: number, address: string]; and we are interested in creating a new type without the first element, like this: type NewTuple = [age: number, address: string]; Is there a way to achieve ...

Combine Typescript files from a dependent module to aid in debugging within a Next.js application

Trying to debug a project written in Typescript using Next.js, but facing issues with bundling TS files from a local dependent common library. Only JS files are included, which is not sufficient for debugging. The goal is to bundle all TS files from the w ...

Dealing with a void method in a React unit test by treating it as an object's property

How can I pass a value to a function in an interface to trigger a click event on an element? I have a React component that I want to write unit tests for: const VariantItem = (props: VariantItem): ReactElement => { return ( <div key={props.produc ...

Is it possible to schedule deployments using Vercel Deploy Hooks in Next.js?

When we schedule a pipeline on git, I want to schedule deploy hooks on vercel as well. Since the app is sending getStaticProps and every HTTP request will be run on every build, I have to rebuild the site to get new results from the server. For instance, ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Error encountered in Next.js: TypeScript error with code ts(7031) - The binding element 'Component' is implicitly assigned the 'any' type

Converting my NextJS project to TypeScript presented a challenge for me. When working on my _app.tsx file, I came across a type error: 'pageProps' implicitly has an 'any' type. ts(7031). The error message likely resembled this image: ht ...

Cheerio fails to retrieve items from the specified directory

My main goal with cheerio is to scrape the titles from this IMDb ranking: Despite following the documentation and specifying the exact HTML path for the titles, I am getting back random and confusing objects like: 'x-attribsNamespace': [Object ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...