构造函数类型

在 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 }
相关推荐
开心不就得了14 小时前
React 状态管理
react.js·typescript
冷冷的菜哥15 小时前
react实现无缝轮播组件
前端·react.js·typescript·前端框架·无缝轮播
lypzcgf1 天前
Coze源码分析-资源库-创建知识库-前端源码-核心组件
前端·typescript·react·coze·coze源码分析·ai应用平台·agent开发平台
患得患失9491 天前
【个人项目】【前端实用工具】OpenAPI to TypeScript 转换器
前端·javascript·typescript
万添裁2 天前
ArkAnalyzer源码初步分析I——分析ts项目流程
typescript·arkanalyzer
凡二人3 天前
Flip-js 优雅的处理元素结构变化的动画(解读)
前端·typescript
烛阴3 天前
【TS 设计模式完全指南】TypeScript 装饰器模式的优雅之道
javascript·设计模式·typescript
YaeZed3 天前
TypeScript7(元组)
typescript
闲云野鹤_3 天前
typeScript学习笔记总结(常用)
typescript
之恒君3 天前
TypeScript(tsconfig.json - references)
typescript