#Looking for a way to make a namespace type extensible in my package

1 messages · Page 1 of 1 (latest)

upbeat mist
#

Hi Guys I’ve got a quick question — I’m a bit new to creating packages.

In my package, I have something like this:

export namespace Path {
export type value = 'AA' | 'BB' | 'CC';
}
I’m exporting Path from my index.ts.

Now my question is — is it possible for users of my package to completely override the value type inside the Path namespace? Basically, I want them to be able to define their own set of values. Is that doable?

tall magnet
#

Yes, this is possible, but janky.

You can add to interface and namespace but can't change a type.

So to extend an union like you want, you would have to build the union from an interface like this

export interface AllowedValues {
  AA: true
  BB: true
  CC: true
}

export type values = keyof AllowedValues

Users will have to do something like, either where they import your module, or in a .d.ts file that they includes in their tsconfig :

declare module 'nameOfYourModule' {
  // here you can add types to 'nameOfYourModule'

  export interface AllowedValues {
    DD: true
    EE: true
  }
}

But note that this only allows you to add, not override (values will be AA | BB | CC | DD | EE in this example).

What you need is probably a generic type. This way the user can pass whatever type, and you in turn build the API with this type parameter.

#

If you elaborate a bit more on your use case I can try and show you how a generic type would be implemented

upbeat mist
#

@tall magnet yes. So Bessically i have a method GlobalSearch(Value:PathType)

export type PathType = "Invoice"|"General"

i want user to extend this type further as per his choise. for Example he can add "Sales " to PathType

So when user use this method. it allow and user shows "Invoice"|"General"|"Sales" in VSC intellisense

upbeat mist
#

one thing is insted of "Invoice"|"General" i want to store values like "All sales order>Invoice>print"|"All transfer order>Invoice>new"