skip to Main Content

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


  1. 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

    import { z } from 'zod';
    const componentSchema = z.string().refine(v => /^(?!.*-v3).*$/.test(v));
    
    function isDeprecatedComponentLibraryImport(input:string) {
      return componentSchema.pasre(input)
    };
    

    zod parse throws errors when the input value isn’t a string or when refine function returns falsy value
    enter image description here

    Login or Signup to reply.
  2. I think you’re looking for the type

    '@ui/components' | `@ui/components/${string}`
    

    This will not just exclude components-v3 but also all other folder names except components.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search