I’m writing a package which will be an extension of another package. The JavaScript is now fully functional, but I want to add typescript library files describing it (Aside: I’ve never written anything in TypeScript, so may have basic thinking errors in what follows). The issue I’m facing is, most of my operations rely on the user “telling me” the name of certain keys.
I want both to restrict my type definitions to use the name they provided and to restrict values in some of my types to the type of whatever that key’s type is in a generic from the other package (which I’m extending).
For example, I want the user (i.e., the person writing software both with the parent package and my extension installed) to be able to say, “Use foo
as the name for the ID field” [where foo
is something arbitrary, but which they previously configured in the parent package], and then I want to be able to,
// file: types.d.ts
type SomeMethodArgs<IdKeyName> = SomeObj & { [IdKeyName]: boolean }
interface OtherMethodArgs<T, IdKeyName> {
bar: typeof ThirdPartyInterface<T>[IdKeyName]
}
So that the user of my package can say, “use foo
“, and then in their IDE (or typescript project) get
type SomeMethodArgs: SomeOtherObj & { foo: boolean }
// ThirdPartyInterface<T> = { foo: string }
type MyIdType: string
Is there some way to do this?
Things I’ve considered:
- Write a generic definition for the entry point function, and have the user specify the args there, and then apply them to the rest of my types (this would be best, but see below)
- Have the user configure the parameters in an environment variable / config file, and import them into
*.d.ts
- mumble mumble mumble something with
symbol
s mumble mumble - write some script the user has to run after installation that “compiles” my
*.d.ts
files with the right parameters (this seems hardest, but if it’s what needs to be done…)
ISTM this must be a not-uncommon problem, so I’m hoping there’s some “standard” way of achieving it, and I’m just now aware of it.
So far, I spent a fair bit of time trying to do it via my first suggestion (trying to let them pass it as a parameter to my main entry point function) before I came here to ask:
export const myMainFunction = ({ idFieldName }) => // do stuff
Because that’s how the JavaScript already works 🙂
But I can’t figure out how to extract it in the types.d.ts
, for example
export declare function myMainFunction<T, I extends keyof ParentLibObject<T>>(args: { idFieldName: I }): void;
export type InitArgs = Parameters<typeof myMainFunction>[0];
export type IdField = Pick<ParentLibObject<T>, InitArgs['idFieldName']>;
But this results in IdField
being {}
, which results in so many downstream errors, I can’t get typescript to --build
it without errors, and therefor can’t even test it the way an end-user would see it.
Thanks for any suggestions, even if not a complete solution, just so I’m pointed in the right direction!