Home > database >  Using custom type props in React
Using custom type props in React

Time:12-11

I have a type that looks like this:

type MyType = string;

I then want to restrict a prop to only take MyType, not a regular string or anything else.

But even when I type it like this:

interface MyProps
{
   key: MyType
}

the component still accepts takes a regular string as a parameter. I guess it's because MyType equals a string.

<MyComponent key="regularstring" />

How do I make the component to only accept 'MyType' type of strings?

CodePudding user response:

Need to provide explicit string for the type. for eg

type MyType = 'myType';

this will only accept the value of myType

for multi values

type MyType = 'myType' | 'regular'; // will support both values
  • Related