Typescript/React: How to define interdependency properties in Interface

You want to define the interface with properties have constraint with each other

You want to define the interface with properties interdependency

You want to define inteface have values interdependency 

Please follow the example code bellow, for every cardType value we is required related fields:

interface ProductCardCommonProps {
interface ProductCardSimple extends ProductCardCommonProps {
cardType: 'simple',
price: number

interface ProductCardOptions extends ProductCardCommonProps {
cardType: 'options',
fromPrice: string,
toPrice: number

interface ProductCardForSale extends ProductCardCommonProps {
cardType: 'forSale',
originPrice: number,
salePrice: number

const ProductCard = (props: ProductCardSimple | ProductCardOptions | ProductCardForSale) => {
return (
<div className="col mb-5">
<Card className="h-100 text-center">
<Badge className="bg-dark position-absolute" style={{top: '0.5rem', right: '0.5rem'}}>Dark</Badge>
<Card.Body className="p-4">
<Card.Title>Fancy Product</Card.Title>
<StarReview star={5} reviewCount={5} />
props.cardType === 'simple' ? `${props.price}đ` :
props.cardType === 'options' ? `${props.fromPrice}đ - ${props.toPrice}đ` :
<span className="text-muted text-decoration-line-through">{`${props.originPrice}đ`}</span>
{` ${props.salePrice}đ`}
<Card.Footer className="p-3 pt-0 border-top-0 bg-transparent">
<a className="btn btn-outline-dark mt-auto" href="#">View options</a>



<ProductCard cardType='forSale' originPrice={40} salePrice={20} /> // valid

<ProductCard cardType='simple' originPrice={40} salePrice={20} /> // error

Nhận xét

Bài đăng phổ biến từ blog này

TypeORM should using repository or query buider ?

Type of children prop in React Typescript

MSAL: Difference between Public Client Application And Confidential Client Application