首页 > 解决方案 > 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

标签: javascriptreactjsvisual-studio-code

解决方案


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 ''
}

推荐阅读