Replies: 1 comment
-
|
Hi again, A solution that came to my mind is to extend the built-in Something like this: const DenoHeaders = Headers;
class SafeHeaders<Keys extends ReadonlyArray<string>> extends DenoHeaders {
public override get<K extends Keys[number]>(key: K) {
return super.get(key);
}
public override set<K extends Keys[number]>(key: K, value: string) {
return super.set(key, value);
}
}
class SaferHeaders<Keys extends Record<string, unknown>> extends DenoHeaders {
public override get<K extends keyof Keys>(key: K) {
return super.get(<string>key);
}
public override set<V extends Keys[K], K extends keyof Keys>(key: K, value: string & V) {
return super.set(<string>key, String(value));
}
}
type MyCustomHeaders = {
'x-usertype-key': 'admin' | 'normal' | 'guest';
'x-another-key': string;
};
type MyCustomHeaderKeys = [keyof MyCustomHeaders];
const unsafe = new DenoHeaders();
const safe = new SafeHeaders<MyCustomHeaderKeys>();
const safer = new SaferHeaders<MyCustomHeaders>();
// -> no care to KEY passed and not suggest KEYS
unsafe.get('x-use');
// -> care to KEY passed and suggest KEYS (and VALUE if nedded)
safe.get('x-usertype-key');
safer.set('x-usertype-key', 'guest');And well, for use outside the file, we can export as follows: // headers.ts
export { ExtendedClass as Headers }
// and import in other files
// then, where this "header" is used,
// the generic-type can be obtained from the top-level module/function/class and passed, if needed
/// or, using global declaration file, if neededIf I accept and need this features, I can do this and apply changes to all related files NOTICE: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, is there a way to use type-safety in using headers or not?
If not, how can I help to develop and add this feature?
Beta Was this translation helpful? Give feedback.
All reactions