首页 > 解决方案 > 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;

Playgrounds
将所有类型设置为任何我仍然最终无法调用的函数类型中缺少的类型

标签: reactjstypescriptinstance

解决方案


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

推荐阅读