typescript泛型

image.png

interface EventMap {
  "select": (id: string) => void;
  "update": () => void;
}
interface IEvent<K extends keyof EventMap> {
  type: string;
  fn: EventMap[K]
}
interface CustomMap<K extends keyof EventMap> {
  [key: string]: IEvent<K>
}

const map: CustomMap = {}

我期望map的key为EventMap的key,value为IEvent结构

阅读 2.3k
2 个回答
interface EventMap {
  "select": (id: string) => void;
  "update": () => void;
}

interface IEvent<K extends keyof EventMap> {
  type: string;
  fn: EventMap[K]
}

type CustomMap = {
  [K in keyof EventMap]: IEvent<K>
}

const map: CustomMap = {}

当然了,也可以整合一下更清爽:

interface EventMap {
  "select": (id: string) => void;
  "update": () => void;
}

type CustomMap = {
  [K in keyof EventMap]: {
    type: string;
    fn: EventMap[K]
  }
}

const map: CustomMap = {}

interface QueryEventMapHandler {
    select: (id: string) => void
    update: () => void
}

interface QueryEvent<K extends keyof QueryEventMapHandler> {
    type: string;
    fn: QueryEventMapHandler[K]
}

type SuperMap = Record<keyof QueryEventMapHandler, QueryEvent<keyof QueryEventMapHandler>>

const map: SuperMap = {
    select: {
        type: 'big',
        fn: (id: string) => { console.log(id) }
    },
    update: {
        type: 'small',
        fn: () => { }
    }
}

要得是这种写法?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题