javascript - PropTypes 不是必需的,但在 VSCode 中按要求显示
问题描述
我最近刚刚在我的 javascript react 项目中添加了一个 jsconfig.json 文件,以获得更好的导入、别名等。现在一切正常,我什至得到了一些增强的类型安全性。我的问题是 VSCode 似乎正在查看函数参数而不是 PropTypes 来检查是否需要道具。在javascript中将参数标记为可选的正确方法是什么?我不能像在 Typescript 中那样只在末尾标记一个问号。代码编译并运行良好,我们只是 VSCode 抱怨。我已经运行了没有任何扩展的 VSCode,所以我知道它不是扩展。
错误是
Property 'className' is missing in type '{ active: true; png: true; }' but required in type '{ [x: string]: any; active: any; className: any; png: any; width?: number; }'.
这是我的文件,我已经简化了代码
// jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"checkJs": true,
"jsx": "react",
"module": "commonjs",
"target": "es6",
"paths": {
"@/*": ["./*"],
"@components/*": ["./common/components/*"]
}
},
"include": ["src/**/*"]
}
// BuildYourTeam.jsx
import React from 'react'
import CreditCard from '@components/CreditCard'
const BuildYourTeam = ({ className }) => {
return (
<div>
<CreditCard active png />
</div>
)
}
export default BuildYourTeam
// CreditCard.jsx
import React from 'react'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import creditCard from '@images/credit_card.png'
import styling from './creditCard.module.scss'
/**
* Simple component for displaying credit card images
*/
const CreditCard = ({ active, className, png, width = 100, ...props }) => {
const classes = classNames(className, 'inline-block', 'relative')
let image
// At smaller sizes the png looks better for active
if (png && active) {
image = (
<img className={styling.active} src={creditCard} width={width} alt='Credit Card' {...props} />
)
}
return (
<div className={classes}>
{image}
<div className={styling.background} />
</div>
)
}
CreditCard.propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
png: PropTypes.bool,
width: PropTypes.number,
}
export default CreditCard
解决方案
import type { FC } from 'react';
...
interface CreditCardProps {
active: boolean;
className?: string;
png: boolean;
width: number
}
const CreditCard: FC<CreditCardProps> = ({ active, className, png, width = 100, ...props }) => {
...
};
使用 defaultProps:
CreditCard.defaultProps = {
className: null, // or ''
}
推荐阅读
- javascript - 在松弛模态视图中显示错误
- java - Java 版本混淆
- html - 非梯形rotate3d视频问题
- javascript - 为什么我的角色权限代码不起作用?(discord.js)
- docker - Lumen Nginx 资产路径问题
- php - 如何使用 $_SESSION 显示消息
- r - 如何根据第二个可能的值范围合并两个数据帧,但保留第一个的值?
- sql - sql查询查找租赁天数大于等于10天的客户
- composer-php - 在 Composer 中创建项目时如何使用全局 composer.json?
- c# - 声音分析仪使用 naudio 进行 48000 个样本/秒的声音。我可以使用 1024 的循环样本大小吗?