获取vue3组件props的typescript类型声明

980 阅读1分钟

用于二次封装类型继承贼方便

// 这里是取消readonly的属性,如果不需要可以忽略
export type TypeNoReadonly<T> = {
  -readonly [K in keyof T]: T[K]
}
export type InstancePropsType<T extends abstract new (...args: any) => any> = Partial<TypeNoReadonly<InstanceType<T>['$props']>>

// 使用,例如需要获取element-plus的组件ElButton的Props类型
import { ElButton } from "element-plus"
type ElButtonType = InstancePropsType<typeof ElButton>

比如我需要一个 MyButton 基于 ElButton 的二次封装

import { ElButton } from "element-plus";
// 这些最好都是放在全局类型声明,然后在这里引入
export type TypeNoReadonly<T> = {
  -readonly [K in keyof T]: T[K];
};
// 这里为了演示就写在一起了
export type InstancePropsType<T extends abstract new (...args: any) => any> = Partial<TypeNoReadonly<InstanceType<T>["$props"]>>;

type ElButtonType = InstancePropsType<typeof ElButton>;
// /* @vue-ignore */ 处理 vue3.3 后解析报错问题
interface Props extends /* @vue-ignore */ ElButtonType {
  // 这里是你扩展的属性
  myattr: string;
  // 这里还可以重置原先ElButton的属性
}
// 这时候的props包含重置和新增属性
const props = defineProps<Props>();
// attrs则刚好包含了所有原始属性方法,就是ElButton的
const attrs = useAttrs();