首页 > 解决方案 > 如何为DefiniteTyped 编写React Native 库的测试?

问题描述

我想为 React Native 的rn-placeholder库做出贡献,为DefinitiveTyped提供类型。这是我第一次index.d.ts向 DefinitiveTyped 贡献文件。

我写了声明文件。现在我想写强制rn-placeholder-tests.ts文件。但是当我尝试使用我的声明时,我得到了regexp错误:

[ts]
Conversion of type 'RegExp' to type 'View' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Property 'measure' is missing in type 'RegExp'.

我什至尝试只复制测试@types/react-native,但它们给出了相同的错误:

import * as React from 'react';
import { Text, View } from "react-native";

class CustomView extends React.Component {
  render() {
    return <View />
  }
}

这是我的tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "lib": ["es6"],
        "noImplicitAny": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "jsx": "react",
        "baseUrl": "../",
        "typeRoots": ["../"],
        "types": [],
        "noEmit": true,
        "forceConsistentCasingInFileNames": true
    },
    "files": ["index.d.ts", "rn-placeholder-tests.ts"]
}

其他文件只是使用npx dts-gen --dt --name my-package-name --template module.

我怎样才能让测试通过?

编辑:我转换rn-placeholder-tests.ts.tsxwhich 摆脱了regexp错误。但是现在 TSLint 抱怨它找不到模块:

[ts] Cannot find module 'react'.
[ts] Cannot find module 'react-native'.
[ts] Cannot find module 'rn-placeholder'.

到底是怎么回事?

标签: typescriptreact-nativetypescript-typingsdefinitelytypedtype-declaration

解决方案


就文件扩展名而言,将 .ts 更改为 .tsx 是正确的举措。(在此处查看有关 tsx 的更多信息:https ://www.typescriptlang.org/docs/handbook/jsx.html )

对于其他“找不到模块”错误,请参阅此“打字稿:找不到模块 'react'”问题

可能是您需要添加类型定义:

npm i -D @types/react

或者,也许您只需将“moduleResolution”添加到您的 tsconfig.json 文件中:

"compilerOptions": {
          ...
          "moduleResolution": "node" <---------- this entry
          ...
}

推荐阅读