#Using provided types throughout a library

1 messages · Page 1 of 1 (latest)

calm gate
#

This is probably a long shot, but I'm hitting a brick wall and this may not be possible, but I at least want a second opinion before I give up.

I'm building a library where I want the user to initialize it using a settings object for their custom settings:

interface IGuildSettings {
    [key: string]: ISetting;
}

Is there any way (and if so, what is the best way?) to make the object they put in be used in other functions throughout the library? For example, if the user does:

mylib.initialize({ hello: {...stuff here...} });

would there be a way to make it so

mylib.setSetting('hello', 1); // Works
mylib.setSetting('nope', 1); // TypeScript errors because nope isn't valid

I would share code, but I got pretty far using a generic/singleton before I realized that obviously that type wouldn't carry over between functions. Any advice?

torn horizon
#

You'd have to capture it in a type variable and then use it later

plucky sonnetBOT
#
JakeBailey#1314

Preview:```ts
interface Guild<T> {
setSetting<K extends keyof T>(
key: K,
value: T[K]
): void
}

declare function createGuild<T>(settings: T): Guild<T>

const guild = createGuild({hello: 1234})

guild.setSetting("hello", 1234)
guild.setSetting("nope", 1234)```

calm gate
#

Wow that is way easier than I was making it out to be. Thanks for such a fast response, I'll try it out now!