简体   繁体   中英

Using custom type props in React

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM