【发布时间】:2021-10-27 04:44:17
【问题描述】:
我正在为外部库编写一个 Typescript 模块。
这是我index.d.ts的一部分
declare module 'my-external-library' {
export class MyComponent extends React.Component<MyComponentProps> {}
export class CustomClass {
constructor(
firstParam: string,
secondParam: string,
)
}
interface MyComponentProps {
config: string
customClass: CustomClass
text?: string
customFn?: (input: string) => boolean
}
}
除了customClass 属性外,这很好用。
自定义类是一个必须是这样的类:
class customClass {
constructor(firstParam, secondParam) {
this.firstParam = firstParam
this.secondParam = secondParam
}
... all the methods you want
}
export default customClass
在一个单独的文件中,我将customClass 属性赋予MyComponent,如下所示:
import customClass from './customClass'
<MyComponent
config: "test"
customClass: customClass
/>
customClass 实际上没有接收到index.d.ts 中声明的“构造函数类型”,但组件的所有其他属性都运行良好。
那么,我所做的类定义是正确的吗?我必须用另一种方法导出类?
这是一个 CodeSandbox:https://codesandbox.io/s/react-typescript-playground-forked-nrfk2
感谢您的帮助,请原谅我的经验不足
【问题讨论】:
-
我不确定我是否正确理解了这个问题,但也许您想扩展 CustomClass?否则customClass实现与CustomClass类型定义没有关系?类 customClass 扩展 CustomClass { ... }
-
可能只是问题中的一个错误,但您的类型定义适用于
CustomClass,而您的js代码适用于customClass(JavaScript IS区分大小写)跨度> -
@RobertDempsey 我明白你在说什么。我的想法是存在这种关系是因为我将道具“customClass”赋予组件
MyComponent。类型检查适用于其他道具,为什么不适用于类?是否必须扩展类以便继承类型? -
感谢您花时间进行设置。恐怕我还是不太明白这个问题。具体来说,我正在查看
ActionProvider.ts。这 是 您定义 ActionProvider 类的地方,并且 ActionProvider 和您的index.d.ts文件之间没有链接,因此它不能继承您根本没有引用的东西。如果您希望您的类推断其变量的类型,您需要执行class ActionProvider extends SomeOtherClass或class ActionProvider implements SomeInterface -
出于好奇,您是否尝试过 MyComponentProps 定义中的
customClass: typeof CustomClass?如果您想将类本身作为值传递,则类型需要是构造函数的类型而不是实例的类型。
标签: javascript typescript types