首页 > 解决方案 > 键入具有来自另一个包的类型的无类型包

问题描述

是否可以重新导出现有的类型化模块并将其类型用于非类型化模块?

我正在导入一个库react-final-form-html5-validation,它只是 typed 的一个小包装器react-final-form

有什么选择吗?

我已经尝试了很多很多东西.......,但这看起来最有希望,但是,react-final-form它没有声明命名空间,所以我不能像使用React下面那样使用它的类型。

project/index.d.ts

/// <reference types="react-final-form" />
//// <reference types="./node_modules/react-final-form/dist/index.d.ts" />
//// <reference path="./node_modules/react-final-form/dist/index.d.ts" />
//// <amd-dependency path="./node_modules/react-final-form/dist/index.d.ts" />
// importing resolves the types, but also turns it into a module, which in turn breaks it
// import * as RFF from react-final-form; 
// import { FieldProps } from react-final-form;
// export * from react-final-form;

declare module 'react-final-form-html5-validation' {
  var Field: React.ComponentType<FieldProps>
}

project/src/index.tsx

import { Field, Abc } from 'react-final-form-html5-validation'
// correct: Module '"react-final-form-html5-validation"' has no exported member 'Abc'

// later in App.render() { return ( .....
      <Field />

// Field is of type React.ComponentType<any>

标签: typescript-typings

解决方案


我也遇到了同样的问题,而且我在打字稿方面不是很有经验,所以我不确定这是否是处理这个问题的正确方法,但我认为我有一个似乎有效的解决方案。

我实现了类型以匹配react-final-form-html5-validation文件中提供的流中的类型,这基本上是 FieldProps,但有一些额外的道具来解释错误消息。我只测试了一点,但它似乎正在工作。正如我所说,我对打字稿还很陌生,只有基本的了解。

declare module 'react-final-form-html5-validation' {
    import { ComponentType } from 'react';
    import { FieldProps } from 'react-final-form';
    type Messages = {
        badInput?: string;
        patternMismatch?: string;
        rangeOverflow?: string;
        rangeUnderflow?: string;
        stepMismatch?: string;
        tooLong?: string;
        tooShort?: string;
        typeMismatch?: string;
        valueMissing?: string;
    };
    export type Html5ValidationFieldProps = FieldProps<any> & Messages;
    export const Field: ComponentType<Html5ValidationFieldProps>;
}

<FieldProps<any>部分取自主要部分,react-final-form这似乎也是从那里导出 Field 元素的方式。


推荐阅读