Vue3 defineEmits 的 emit TS 类型获取

214 阅读1分钟
// 泛型 EmitFunction 类型
type EmitFunction<T, K extends keyof T> = (evt: K, ...args: T[K]) => void;

// 辅助类型:将联合类型转换为交叉类型
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void
  ? I
  : never;

// 泛型 EditorEmitFunction 类型
declare type VueEmit<T> = UnionToIntersection<
  {
    [K in keyof T]: EmitFunction<T, K>;
  }[keyof T]
>;
// type.ts
interface Props {
  modelValue?: string;
}
interface Emits {
  'update:modelValue': [editorValue?: string];
}
// vue
const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits<Emits>();

useProps(props, emit)
// hooks.ts
export function useProps(props:Props, emit:VueEmit<Emits>) {}