【问题标题】:Type checks not working in a create-react-app typescript project类型检查在 create-react-app 打字稿项目中不起作用
【发布时间】:2021-09-11 09:40:00
【问题描述】:

我使用命令 npx create-react-app my-app --template typescript 创建了一个新的 react 项目。然后引入了一些类型错误,但 yarn build 没有发现这些错误。

我所做的改变是

  1. src目录下新建文件test.tsx,内容如下
type Props = {
  message: string
}

export function getValue(props: Props): string {
  return props.message1
}
  1. 从 index.tsx 调用上述函数
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {getValue} from "./test"

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

console.log(getValue({message: "test"}))
  1. 运行yarn build,它不会抛出任何打字错误

Github 存储库 - https://github.com/kanagarajkm/my-app-ts

非常感谢这里的任何帮助。谢谢。

【问题讨论】:

标签: reactjs typescript create-react-app


【解决方案1】:

Create-react-app 的 typescript 模板仅使用 typescript 进行类型检查。在开发应用程序时,您可以在 IDE(如果它支持 typescript 语言服务器)中看到 typescript 错误。或者直接从命令行运行tsc

build 脚本将babel-loaderpreset-typescript 一起用于transpiling only。这意味着如果 typescript 代码在语法上是正确的(但可能无法通过类型检查),则无论任何 typescript 错误,它都将被转换为.js 文件。

如果您只想在成功进行类型检查后构建您的包,您可以修改react-scripts buildpackage.json 构建命令,使其在tsc 完成且无错误后运行:

...
    "scripts": {
        ...
        "build": "tsc && react-scripts build",
        ...
    },
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-05
    • 2021-07-06
    • 2019-03-16
    • 2018-09-16
    • 2018-12-21
    • 2018-11-03
    • 2018-11-08
    • 2018-04-30
    相关资源
    最近更新 更多