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.Img
variant="top"
src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg"
alt="..."
/>
<Card.Body className="p-4">
<Card.Title>Fancy Product</Card.Title>
<StarReview star={5} reviewCount={5} />
<Card.Text>
{
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.Text>
</Card.Body>
<Card.Footer className="p-3 pt-0 border-top-0 bg-transparent">
<Card.Title>
<a className="btn btn-outline-dark mt-auto" href="#">View options</a>
</Card.Title>
</Card.Footer>
</Card>
</div>
)
}

==============================

Using


<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

Why we should Avoid using UNSAFE componentWillMount, componentWillReceiveProps, componentWillUpdate