I will be parsing my code to an AST and looking for imports. The imports I am looking for will be ones that do not include -v3
at the end of them.
@ui/components <- this will match
@ui/components/forms/field <- this will match
@ui/components-v3 <- this should not match
@ui/components-v3/forms/field <- this should not match
Now what I want to do is create a typeguard which will look at these import declarations and assert that they are indeed of this form, then return that as an interpolated string. e.g.,
function isDeprecatedComponentLibraryImport(importPath: string): importPath is `@ui/components${string}`;
The problem I am running into here is that I want the inverse of this; I want it to return that the string in question matches @ui/components${string}
and not @ui/components-v3${string}
I could make a complement
function that returns the inverse but that’s not ideal because that will just say that the string is definitely not @ui/components-v3${string}
, not that it is @ui/components${string}
Is this possible in typescript?
2
Answers
Hope this is what you’re looking for 🙂
^(?!.*-v3).*$
Edit: the flavor is wrong in the screenshot, but I checked after taking it that javascript behaves the same way
Edit2: for the string validation I would suggest actually working with something like zod. where you can declare a schema for the component string
zod parse throws errors when the input value isn’t a string or when refine function returns falsy value
I think you’re looking for the type
This will not just exclude
components-v3
but also all other folder names exceptcomponents
.