Skip to content

Commit

Permalink
Extend type-safety to event callbacks 💪
Browse files Browse the repository at this point in the history
  • Loading branch information
wotschofsky committed Dec 19, 2022
1 parent e4c0471 commit 5a9bc71
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/modules/ConsentManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ interface CookieData {

type EventNames = 'update' | 'grant' | 'revoke';

type UpdateEventCallback = (id: string) => void;
type UpdateEventCallback<G extends String> = (id: G) => void;

export interface ConsentManagerConfig<G extends string> {
version: string;
Expand All @@ -75,7 +75,7 @@ export default class ConsentManager<G extends string = string> {
public config: ConsentManagerConfig<G>;
public isCustomized = false;
public grants: GrantsStatus<G>;
private eventListeners: Record<string, UpdateEventCallback[]> = {};
private eventListeners: Record<string, UpdateEventCallback<G>[]> = {};

constructor(config: ConsentManagerConfig<G>) {
this.config = merge(defaultConfig, config);
Expand Down Expand Up @@ -127,12 +127,12 @@ export default class ConsentManager<G extends string = string> {
});
}

public setGrant(id: string, status: boolean): void {
public setGrant(id: G, status: boolean): void {
// Set all grants
if (id === '*') {
// Call recursively for all categories
for (const key of Object.keys(this.grants)) {
this.setGrant(key, status);
this.setGrant(key as G, status);
}
return;
}
Expand Down Expand Up @@ -161,7 +161,7 @@ export default class ConsentManager<G extends string = string> {
this.writeCookie();
}

public on(eventName: EventNames, callback: UpdateEventCallback): void {
public on(eventName: EventNames, callback: UpdateEventCallback<G>): void {
// Add empty array for event listeners if missing
if (!(eventName in this.eventListeners)) {
this.eventListeners[eventName] = [];
Expand All @@ -170,7 +170,7 @@ export default class ConsentManager<G extends string = string> {
this.eventListeners[eventName].push(callback);
}

public off(eventName: EventNames, callback: UpdateEventCallback): void {
public off(eventName: EventNames, callback: UpdateEventCallback<G>): void {
// Ignore if no listeners are registered for event
if (
!(eventName in this.eventListeners) ||
Expand All @@ -184,7 +184,7 @@ export default class ConsentManager<G extends string = string> {
this.eventListeners[eventName].splice(callbackIndex, 1);
}

private dispatch(eventName: EventNames, grant: string): void {
private dispatch(eventName: EventNames, grant: G): void {
// Ignore if no listeners are registered for event
if (!(eventName in this.eventListeners)) {
return;
Expand Down

0 comments on commit 5a9bc71

Please sign in to comment.