打字稿反应道具验证不起作用
typescript react props validation not working
我是打字稿的新手,似乎无法弄清楚这个问题。我已经创建了一个界面并检查了道具。如果 props 为空,它可以工作,但我期待一个字符串,如果传递了数字,它不会给出任何错误。
type Props = {
name: number;
};
const ProductListItem = ({ name }: Props): JSX.Element => {
return (
<div className="product">
<h4>{name}</h4>
</div>
);
};
export default ProductListItem;
像这样使用这里的组件
import "./ProductList.scss";
import ProductListItem from "./ProductListItem";
interface Product {
_id: string;
itemName: string;
}
type Props = {
allProducts: Array<Product>;
};
const ProductList = ({ allProducts }: Props): JSX.Element => {
console.log(allProducts);
const productsTodisplay = allProducts.map((product: any) => (
<ProductListItem key={product._id} title={product.itemName} />
));
return <section className="productsContainer">{productsTodisplay}</section>;
};
export default ProductList;
为了在 React Functional Component
中进行正确的类型检查,您可以将其类型添加到 generic type parameter
像这样:
import React, { FunctionComponent } from "react";
type Props = {
name: number;
};
const ProductListItem: FunctionComponent<Props> = ({ name }) => {
return (
<div className="product">
<h4>{name}</h4>
</div>
);
};
export default ProductListItem;
我是打字稿的新手,似乎无法弄清楚这个问题。我已经创建了一个界面并检查了道具。如果 props 为空,它可以工作,但我期待一个字符串,如果传递了数字,它不会给出任何错误。
type Props = {
name: number;
};
const ProductListItem = ({ name }: Props): JSX.Element => {
return (
<div className="product">
<h4>{name}</h4>
</div>
);
};
export default ProductListItem;
像这样使用这里的组件
import "./ProductList.scss";
import ProductListItem from "./ProductListItem";
interface Product {
_id: string;
itemName: string;
}
type Props = {
allProducts: Array<Product>;
};
const ProductList = ({ allProducts }: Props): JSX.Element => {
console.log(allProducts);
const productsTodisplay = allProducts.map((product: any) => (
<ProductListItem key={product._id} title={product.itemName} />
));
return <section className="productsContainer">{productsTodisplay}</section>;
};
export default ProductList;
为了在 React Functional Component
中进行正确的类型检查,您可以将其类型添加到 generic type parameter
像这样:
import React, { FunctionComponent } from "react";
type Props = {
name: number;
};
const ProductListItem: FunctionComponent<Props> = ({ name }) => {
return (
<div className="product">
<h4>{name}</h4>
</div>
);
};
export default ProductListItem;