Home > OS >  Typescript: using array values as union for related prop
Typescript: using array values as union for related prop

Time:06-13

I have the following React component

const Pagination = <P extends number[] = [10, 25, 50, 100]>(props: {
    perPageVariants?: P,
    perPageDefault?: P[number],
}) => 
{
    // ....
}

It works perfectly with default value for perPageVariants prop and doesn't allow to use wrong value for perPageDefault. But if I set custom perPageVariants values, perPageDefault continues to allow only value from defaults.

<Pagination 
    perPageVariants={[123, 456]} 
    perPageDefault={100}
/>
// it works, but should throw an error 

Is it possible to do this somehow with Typescript?

CodePudding user response:

You just need to infer each element in the tuple:

import React from 'react'

const Pagination = <P extends number[] = [10, 25, 50, 100]>(props: {
  perPageVariants?: [...P],
  perPageDefault?: [...P][number],
}) => {
  return null
}

<Pagination perPageDefault={1} perPageVariants={[123, 456]} />;// expected error
<Pagination perPageDefault={123} perPageVariants={[123, 456]} />; // ok

enter link description here

  • Related