【问题标题】:Type an untyped package with types from another package键入具有来自另一个包的类型的无类型包
【发布时间】:2019-02-22 19:22:33
【问题描述】:

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

我正在导入一个库 react-final-form-html5-validation,它只是键入 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


    【解决方案1】:

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

    我实现了类型以匹配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>;
    }
    

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

    【讨论】:

    • 你把这个内容放在哪里?当我将它写入顶级 index.tsx 文件时,它显示Invalid module name in augmentation. Module 'react-final-form-html5-validation' resolves to an untyped module
    • @Qwerty 哦,对不起,我有一个globals.d.ts 文件,我在其中放置了与没有完整打字稿支持的模块相关的任何内容。我正在使用create-react-app,它们具有开箱即用的打字稿支持,所以我不确定打字稿的配置中是否有一些东西可以确保它选择这样的定义。
    猜你喜欢
    • 2016-10-21
    • 2020-06-21
    • 2011-04-13
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2020-09-30
    • 2021-10-24
    • 2016-07-26
    相关资源
    最近更新 更多