Initializing generic type inside generic class in Typescript

对着背影说爱祢 提交于 2020-01-06 08:09:09

问题


I want to initialize a generic class variable inside a generic class using a generic type, but I can't figure out if there is a way to do this.

Initializing with types works fine, it doesn't seem like it work with generics though.

type EventCallback<I, O> = (event: I) => O;

type ListenerList<K extends string | symbol | number, I, O, V extends EventCallback<I, O>> = {
    [T in K]: V[];
};

const test: ListenerList<string, string, string, (event: any) => any> = {}; // Works fine

export default class EventProcesser<
  K extends string | symbol | number,
  I,
  O,
  V extends EventCallback<I, O>
> {
  private listeners: ListenerList<K, I, O, V> = {}; // Error :(
}

I get the following error Type '{}' is not assignable to type 'ListenerList<K, I, O, V>'. Is there a way to do this?


回答1:


K can be a string literal type, so EventProcesser<'prop', ..> is valid meaning that listeners must have property named prop. This means that your default will not be valid for any K passed in as it should be.

You can use Partial to let the compiler know that no properties will be required:

type EventCallback<I, O> = (event: I) => O;

type ListenerList<K extends string | symbol | number, I, O, V extends EventCallback<I, O>> = {
    [T in K]: V[];
};

const test: ListenerList<string, string, string, (event: any) => any> = {}; // Works fine

export default class EventProcesser<
    K extends string | symbol | number,
    I,
    O,
    V extends EventCallback<I, O>
    > {
    private listeners: Partial<ListenerList<K, I, O, V>> = {}; // ok
}


来源:https://stackoverflow.com/questions/56222509/initializing-generic-type-inside-generic-class-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!