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呈现一个react组件。

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喜欢here所述的内容,而没有任何更改。

const Box: InstanceType = Object.assign(
 (props: CSS.properties) => boxInstance.render(props),{
   as: function as(asProp: AsType) {
    return instance.as(asProp);
   }
 }
)

Typescript Playground

已编辑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;

游乐场
将所有类型设置为我仍然以cannot invoke as functionas is missing in type结尾的任何类型。

解决方法

如果更改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);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...