Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support class auto import with its type #439

Open
3 tasks done
otomad opened this issue Nov 7, 2023 · 3 comments
Open
3 tasks done

Support class auto import with its type #439

otomad opened this issue Nov 7, 2023 · 3 comments
Labels
enhancement New feature or request

Comments

@otomad
Copy link

otomad commented Nov 7, 2023

Clear and concise description of the problem

If declare and export a class.

export default class Foo {

}

While directly use it for construct a new instance. Yeah it works properly.

const foo = new Foo();

However if use this class for type hint, TypeScript will not recognize it.

const foo: Foo = new Foo();
           ^^^

function myFunc(foo: Foo) {
                     ^^^
}

Error: 'Foo' refers to a value, but is being used as a type here. Did you mean 'typeof Foo'?

typeof Foo will be the type of Foo's constructor, that is new () => Foo, like StringConstructor of String;

You have to import that class explicitly, then it will work.

import type Foo from "../classes/Foo";

Suggested solution

Do not use typeof import(xxx) in the auto-imports.d.ts, use export xxx from instead. Just like it in latest Nuxt auto import method.

const Foo: typeof import('../classes/Foo')['default'];

change to

export Foo from '../classes/Foo';

Alternative

No response

Additional context

No response

Validations

@otomad otomad added the enhancement New feature or request label Nov 7, 2023
@ZiFy
Copy link

ZiFy commented Mar 9, 2024

我也遇到了相同的问题,现在有解决方案吗?
I ran into the same problem, is there a solution now?

@hf-xz
Copy link

hf-xz commented Apr 2, 2024

My solution using InstanceType:

// Api.ts
export class Api {
  ...
}

// auto-imports.d.ts
declare global {
  ...
  const Api: typeof import('./src/apis/Api')['Api']
}

// other file
let someApi: InstanceType<typeof Api> = new Api()

// or
type ApiType = InstanceType<typeof Api>
let someApi: ApiType = new Api()
function myFunc(api: ApiType) {
  ...
}

@tohere
Copy link

tohere commented Apr 12, 2024

我也有这个问题, 当我使用导入 threejs 中的部分类的时候会报这个错, 如果不加 type, 那就是导入的类, 如果加上 type, 那就是导入的类型, 希望能有个参数控制两者都能使用

 AutoImport({
	imports: [
		{
	      from: 'three',
	      imports: ['Group'],
		 // type: true
	    }
	]
} )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants