0%

typescript-stop-running-app-on-type-error

公司的项目是基于React,今天周末闲着没事用Vite搭建了一个React项目,在运行的时候,突然发现,即使typescript类型匹配,程序竟然也没有报错,于是突发奇想,能不能在类型不匹配的时候停止运行并报错呢?

代码很简单,首先我定义了一个Card组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React, {ReactNode} from 'react'

interface CardProps {
title: string;
content: string;
children?: ReactNode;
}

export function Card(props: CardProps) {
return (
<div className="card">
<h2>{props.title}</h2>
<p>{props.content}</p>
<p>{props.footer}</p>
{props.children}
</div>
)
}

在返回的组件中,我故意使用了一个CardProps中没有的属性 - footer。此时运行程序,你会发现一切正常!
这有点不合逻辑呀,应该报错才是,于是对着AI一番操作,找到如下方法:

首先安装vite-plugin-checker

1
npm install --save-dev vite-plugin-checker

然后在vite.config.ts中添加如下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
import {defineConfig} from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker';

// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
checker({
typescript: true,
}),
],
})

再次运行npm run dev,你会发现控制台给出类型不匹配的报错了, 浏览器中的页面也给出了报错,这才是我想要的结果呀!

有的建议在tsconfig.json中开启strict: true模式,其实和这个选项无关。typescript是静态类型检查,只在编译时有作用,运行时已经没有typescript了,所以只能靠打包工具来控制是否报错,比如vite或者webpack等。