Michele Grisafi
Michele Grisafi

Reputation: 169

Typescript with PropTypes in React throws error with enums

I'm having some issues with defining the PropTypes for a string enumerator. I have the following type in Typescript:

state: "pending"|"accepted"|"rejected",

and the corresponding propType:

state: PropTypes.oneOf(["pending","accepted","rejected"]).isRequired,

This, however throws the following error: "Type 'string' is not assignable to type '"pending" | "accepted" | "rejected"'.ts(2322)". I really don't know what to do! Thanks in advance for any help you can give me.

Upvotes: 0

Views: 478

Answers (1)

hanan
hanan

Reputation: 1880

Issue is state has type "pending"|"accepted"|"rejected" and its not Enum its Union type and["pending","accepted","rejected"] has type string[]

you have to Tell Typescript its "pending"|"accepted"|"rejected" [] not string[]

For convenience I'm going to create a new type

type State = 'pending' | 'accepted' | 'rejected';

state: State = 'pending'

// we have to tell typescript its type is not string[] but State[] 
state: PropTypes.oneOf(['pending','accepted','rejected'] as State[]).isRequired

here is Example that I have created for you.

Upvotes: 1

Related Questions