构造函数类型

在 TypeScript 中,可以单独声明构造函数的类型。构造函数类型通常用于描述如何创建类的实例,可以使用 new关键字来定义构造函数的类型。

定义构造函数类型

ts 复制代码
// 定义一个构造函数类型 
type PersonConstructor = { new (name: string, age: number): Person; }; 
// 定义 Person 类 
class Person { 
    name: string; 
    age: number; 
    constructor(name: string, age: number) { 
        this.name = name; 
        this.age = age; 
    } 
}

new (name: string, age: number): Person:这表示构造函数接受两个参数 nameage,并返回一个 Person 类的实例。

使用构造函数类型

ts 复制代码
// 声明一个变量,其类型为 PersonConstructor 
let createPerson: PersonConstructor; 
// 赋值为 Person 类的构造函数 
createPerson = Person; 
// 使用构造函数创建 Person 实例 
const person = new createPerson('John', 30); 
console.log(person); // 输出: Person { name: 'John', age: 30 }
相关推荐
Kitasan Burakku1 天前
Typescript return type
前端·javascript·typescript
星光不问赶路人2 天前
一文搞清楚 TypeScript 中 triple-slash 与 tsconfig.types 有何区别?
typescript·vite
duansamve5 天前
React 18+TS中使用Cesium 1.95
react.js·typescript·cesium
岁岁岁平安5 天前
SpringBoot3+WebSocket+Vue3+TypeScript实现简易在线聊天室(附完整源码参考)
java·spring boot·websocket·网络协议·typescript·vue
简小瑞6 天前
VSCode 源码解密:一个"无用"属性背后的精妙设计
typescript·visual studio code
FogLetter6 天前
TypeScript 泛型:让类型也拥有“函数式”超能力
前端·typescript
Keepreal4967 天前
Typescript中type和interface的区别
前端·typescript
huangql5207 天前
UniApp + Vite + Vue3 + TypeScript 项目中 ESLint 与 Prettier 的完整配置指南
vue.js·typescript·团队开发·代码规范
带娃的IT创业者7 天前
TypeScript + React + Ant Design 前端架构入门:搭建一个 Flask 个人博客前端
前端·react.js·typescript
星光不问赶路人8 天前
project references在tsserver内工作流程
typescript·visual studio code