当前位置: 首页 > 知识库问答 >
问题:

javascript - typescript的InstanceType<type>怎么用呀?

公羊子真
2023-05-16

今天在用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

共有3个答案

须景胜
2023-05-16

作用是用构造函数的类型推断其实例的类型,InstanceType<new (...args) => T>的结果就是T

当你定义一个class Person,同时

  • 定义了其构造函数Person
  • 声明了其构造函数类型typeof Person
  • 声明了其实例类型Person

所以,InstanceType<typeof Person>即是类型Person

在vue中需要InstanceType<typeof Component>得到组件实例类型,而不是直接用Component作为类型,是因为Component不是class,它只是一个构造函数,他没有声明实例类型。

东方栋
2023-05-16

官方文档看一下:https://www.typescriptlang.org/docs/handbook/utility-types.ht...

萧韬
2023-05-16

InstanceType<Obj> 表示类型为 Obj 对象的实例。

具体到你的用法,InstanceType<typeof Person> 就相当于 Person 类型,所以 p1 没错。

到了 p2,你将一个 Person 类型的对象赋值给了 typeof Person 类型的对象,所以会报错 类型 "Person" 中缺少属性 "prototype",但类型 "typeof Person" 中需要该属性。ts(2741)

 类似资料: