Home > other >  How can I initialized the generics attribute of object?
How can I initialized the generics attribute of object?

Time:10-28

I have the code like below

class Eventful<T extends string> {
  // ↓ How can I initialized this attr without ts error?
  private eventMap: Record<T, (args?: any) => void> = ?
}

Or

class Eventful<T extends string> {
  private eventMap!: Record<T, (args?: any) => void>

  constructor() {
    this.eventMap = ?
  }
}

so, what I should do? thx.

I try to initialized the attribute with

function addEvent(key: T, handler: (args?: any) => void>) {
  this.eventMap = {
    [key]: [] as EventHandler[]
  }
}

but it also cause error with ts(2322) in VSCode.

CodePudding user response:

I think for the declaration you should use as to prevent repeating of the type:

class Eventful<T extends string> {
    private eventMap = {} as Record<T, ((args?: any) => void)[]>;
}

also, it should be a Record of strings to arrays of functions. Then you can use push to add the handler in addEvent:

    addEvent(key: T, handler: (args?: any) => void) {
        if (!(key in this.eventMap)) this.eventMap[key] = [];

        this.eventMap[key].push(handler);
    }

Playground

  • Related