unplugin-auto-import
unplugin-auto-import copied to clipboard
Support class auto import with its type
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
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guide.
- [x] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
我也遇到了相同的问题,现在有解决方案吗? I ran into the same problem, is there a solution now?
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) {
...
}
我也有这个问题, 当我使用导入 threejs 中的部分类的时候会报这个错, 如果不加 type, 那就是导入的类, 如果加上 type, 那就是导入的类型, 希望能有个参数控制两者都能使用
AutoImport({
imports: [
{
from: 'three',
imports: ['Group'],
// type: true
}
]
} )