H5W3
当前位置:H5W3 > 问答 > 正文

typescript泛型

typescript泛型

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

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 = {}

回答

本文地址:H5W3 » typescript泛型

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址