typescript泛型

hold_baby
  • 2.9k

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结构

回复
阅读 915
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: () => { }
    }
}

要得是这种写法?

宣传栏