typescript的InstanceType<type>怎么用呀?
今天在用element-plus写表单的时候,老师在用ref获取组件以后, 下面写的是
const formRef = ref<InstanceType<typeof ElForm>>()在网上搜了很多也不明白这个InstanceType<type>到底怎么用,以及下面的两种用法有什么区别吗
type PersonType1 = InstanceType<typeof Person>
const p1: PersonType1 = new Person('tom', 22)
type PersonType2 = typeof Person
const p2: PersonType2 = new Person('23', 2)
谢谢各位!! T T
回复
1个回答
test
2024-07-03
作用是用构造函数的类型推断其实例的类型,InstanceType<new (...args) => T>的结果就是T
当你定义一个class Person,同时
- 定义了其构造函数
Person - 声明了其构造函数类型
typeof Person - 声明了其实例类型
Person
所以,InstanceType<typeof Person>即是类型Person。
在vue中需要InstanceType<typeof Component>得到组件实例类型,而不是直接用Component作为类型,是因为Component不是class,它只是一个构造函数,他没有声明实例类型。
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容