Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6288

TypeScript - is it possible validate string types based on pattern matching or even length?

$
0
0

Consider the following component, which uses a library called styled-components to create a prestyled Text component:

const StyledText = styled(Text)`  font-family: Roboto;  color: ${(props: ITextProps) => props.color || '#000' }; `

where ITextProps is:

interface ITextProps {  color: string;}

Is there a way to enforce that only valid hex strings are passed to my component?

Ideally the color prop should always match the pattern /#\d{3}(\d{3})?/g, a # followed by at least 3 digits and optionally 3 more digits. If that's not possible, then is there a way to at least enforce that the string is either 4 or 7 characters long?

My research has brought me to a dead end so I'm wondering if anyone on SO might know how I can implement this behavior in TypeScript.


Viewing all articles
Browse latest Browse all 6288

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>