reactjs - Typescript:如何通过自动完成向函数动态添加方法?
问题描述
作为 Typescript 的新手,我无法理解如何将方法附加到函数。该代码有效,但类型未正确导出以进行自动完成。可以请人帮忙并告诉我我做错了什么吗?
import * as CSS from 'csstype';
export type AsType = 'div' | 'span' | 'main';
export interface InstanceType {
/**
* Set HTML tag
* @param as Tag or component
*/
as: (tagName: AsType) => any;
}
// base has methods render(props: CSS.Properties) and as(a: AsType)
const boxInstance = new Base();
function attachMethods(Component, instance) {
Component.as = function as(asProp: AsType) {
return instance.as(asProp);
}
}
function Box(props: CSS.Properties): InstanceType {
return boxInstance.render(props);
}
attachMethods(Box, boxInstance);
在另一个模块中 Box 是这样导入的,但自动完成不起作用。我使用 Microbundle,所以应该正确创建 *.d.ts。Box 渲染一个反应组件。
import { Box } from 'package';
// autocompletion or JSDoc does not work here
const Boxi = Box.as('div');
// returns <div>Box</div>
<Boxi>Box</Boxi>
也尝试过 Object.assign 喜欢这里描述的没有任何改变。
const Box: InstanceType = Object.assign(
(props: CSS.properties) => boxInstance.render(props),
{
as: function as(asProp: AsType) {
return instance.as(asProp);
}
}
)
28.08 年编辑
根据 Aluan Haddad 的回答,JSDoc 的参数名称是错误的。它应该是。但是 JSDoc 无法正常工作,因为 InstanceType 不正确。请参阅 ccarton 的答案。
* @param tagTame - Tag or component
编辑 29.08 尝试了一种解决方法。这消除了打字稿错误并且 TSDoc 有效。
interface ComponentType extends InstanceType {
(props: CSS.Properties): any // or ReturnType<typeof render> function
}
const Box: ComponentType = function Box(props: CSS.Properties) {
return box.render(props);
} as ComponentType;
解决方案
如果您更改attachMethods
为返回修改后的对象,您可以通过一些类型转换来实现您想要的。我们还应该使用Object.defineProperty
最安全的方式来修改现有对象:
function attachMethods<T> (component: T, instance: InstanceType): T & InstanceType {
Object.defineProperty(component, 'as', {
value: (asProp: AsType) => instance.as(asProp)
})
return component as any
}
function BoxFunction (props: CSS.Properties): InstanceType {
return boxInstance.render(props);
}
const Box = attachMethods(BoxFunction, boxInstance);
推荐阅读
- postgresql - 使用 Python 代码将带有偏移量的日期插入 PostgreSQL 数据库
- javascript - 使用 ajax 和 laravel 提交表单
- javascript - AngularJS 重定向控制器和历史回溯问题
- html - 面临使用 VBA 从网站中提取数据的问题
- python - 在同一个表的报告中添加更多 id
- javascript - 使用 Gauge / Taiko 通过 removeAttribute('readonly') 自动化日期选择器
- amazon-web-services - 尝试使用 awsmobile init 初始化项目
- ios - Xamarion.iOS - statusBar 如何改变文本颜色?
- azure-log-analytics - 在 Azure Log Analytics 的查询中解析 IIS 日志
- fortran - 为什么不引发浮点异常 (FPE)?