问题
如何从.d.ts声明文件中的库导入类型?
背景
我正在编写一个cf.d.ts文件,为我的应用程序保存一个具有通用类型的自定义命名空间。这样,我不需要在任何地方导入我想要引用的Foo模块
declare namespace CF {
export type Foo = number
}对于包装原语的类型(或我的声明文件中的其他自定义类型),这足够有效。但是,我现在想提到来自我所依赖的包的类型。在本例中,我想引用来自Instance包的IAnyType和mobx-state-tree类型:
declare namespace CF {
/**
* Represents the parameters to a query
*/
export type QueryParams<
F extends Instance<IAnyType>,
R extends Instance<IAnyType>,
> = [F[], R[], number]
}正如所写的,Instance和IAnyType被推断为any,因为TS不知道这些类型来自何处。在这些类型上获得准确的键入的唯一方法是将import('mobx-state-tree').添加到这些类型的每一种用法中:
declare namespace CF {
/**
* Represents the parameters to a query
*/
export type QueryParams<
F extends import('mobx-state-tree').Instance<import('mobx-state-tree').IAnyType>,
R extends import('mobx-state-tree').Instance<import('mobx-state-tree').IAnyType>,
> = [F[], R[], number]
}出于明显的原因,我想避免这种冗长,并将它们导入到声明中的一个位置,然后引用它们,但是如果我import { ... } from 'mobx-state-tree',那么任何引用CF命名空间的模块都无法看到QueryParams类型。
我尝试过的其他事情:
import type { ... } from 'mobx-state-tree'/// <reference types="mobx-state-tree" />import MST = require('mobx-state-tree') (然后使用MST.Instance<...>))
发布于 2022-10-03 13:32:07
我不知道您现在是否已经解决了这个问题,但是添加导入的问题是它将d.ts从一个script (全局)更改为一个module (本地)声明。使此工作的方法是将类型包装在declare global中。
import type { Instance, IAnyType } from 'mobx-state-tree'
declare global {
namespace CF {
/**
* Represents the parameters to a query
*/
export type QueryParams<
F extends Instance<IAnyType>,
R extends Instance<IAnyType>,
> = [F[], R[], number]
}
}https://stackoverflow.com/questions/68954975
复制相似问题