如何为DefinitelyTyped编写React Native库的测试?

时间:2018-11-19 12:56:43

标签: typescript react-native typescript-typings definitelytyped type-declaration

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

我写了声明文件。现在,我要编写强制性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转换为.tsx,摆脱了regexp错误。但是现在TSLint抱怨找不到模块:

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

这是怎么回事?

1 个答案:

答案 0 :(得分:2)

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

对于其他“找不到模块”错误,请参见此"typescript: Cannot find module 'react'" issue

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

npm i -D @types/react

或者,也许您只需要在tsconfig.json文件中添加“ moduleResolution”即可:

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