Home > Back-end >  Can't use the type with 'import type'
Can't use the type with 'import type'

Time:02-20

This is a method definition:

// aFunc.ts
const aFunc = async (input: string) => {
  return { name: input };
};

export default aFunc;

I want to use the type of this func in another file using import type:

import type aFunc from './aFunc';

type API = {
  getName: aFunc;
};

I get 'aFunc' refers to a value, but is being used as a type here. Did you mean 'typeof aFunc'? error when I use this.

What am I missing? Is there a tsconfig option to enable this? I'm using TypeScript 4.5.5.

CodePudding user response:

The correct syntax for importing type information is one of the following:

// type modifier on import names (for mixing with value imports):
import {type Type} from './module';

// importing exclusively types in the statement:
import type {Type} from './module';

The way to do this in your example is to create the type you want to export so that you can import it in another module:

TS Playground

// aFunc.ts

export type AFunc = <T extends string>(input: T) => Promise<{ name: T }>;

const aFunc: AFunc = async name => ({ name });

// Or, you could write it like this:
// const aFunc = async <T extends string>(input: T) => ({ name: input });
// export type AFunc = typeof aFunc;

export default aFunc;
// module.ts

import {type AFunc} from './aFunc';

type API = {
  getName: AFunc;
};

Edit:

You can import only the type information related to a value by using the type import modifier when importing the value... however, this only means that you don't have access to the value (but you can still use its type-related information):

// lowercase aFunc is the function value which is exported as the default export in your example:
import {type default as aFunc} from './aFunc';

type API = {
  getName: typeof aFunc;
};
  • Related