Search code examples
reactjstypescripttypescript-typingsreact-propsreact-proptypes

What is the TypeScript declaration equivalent of PropTypes.arrayOf?


I wish to convert PropTypes to Typecript declaration.

I could find the equivalent for most of them, but this one I don't know:

fruits: PropTypes.arrayOf(PropTypes.oneOf(['apple', 'banana', 'cherry', 'dewberry']))

My best attempt is:

fruits: any[]

But it should be specific for the listed items.

The following ones could be valid and invalid values for property fruits:

// Valid
fruits: ['apple']
fruits: ['cherry', 'dewberry']
// Invalid
fruits: ['my', 'little', 'pony']

Thank you for your help!


Solution

  • Something like this:

    type fruit = 'apple' | 'banana' | 'cherry' | 'dewberry'
    
    type fruits = fruit[]
    
    const a:fruits = ['apple'] // ok
    const b:fruits = ['cherry', 'dewberry'] // ok
    const c:fruits = ['my', 'little', 'pony'] // error
    

    Try it out on the TS playground.