如何正确实现TypeScript构造签名,使函数支持new关键字调用?
实现可同时通过
new调用和直接调用的函数 你的AccountConstructor类型同时定义了构造签名(用new调用)和调用签名(直接调用),所以需要实现一个同时满足这两种调用方式的函数。下面是正确的实现方案:
正确代码实现
type Account = { username: string password: string } type AccountConstructor = { new (username: string, password: string): Account (username: string, password: string): Account } // 实现同时支持new和直接调用的函数 const Account: AccountConstructor = function(username: string, password: string) { // 用new.target区分调用方式 if (new.target) { // 作为构造函数时,给实例绑定属性 this.username = username; this.password = password; } else { // 直接调用时返回普通对象 return { username, password }; } } as AccountConstructor; // 类型断言告诉TS该函数符合AccountConstructor类型 // 测试两种调用方式 const accountFromNew = new Account('alice', '123456'); const accountFromCall = Account('bob', '654321');
原有代码报错原因
- 普通函数赋值报错:TypeScript默认认定普通函数不具备构造签名(无法用
new调用),因此无法匹配AccountConstructor中的new签名要求。 - 类赋值报错:类的类型仅包含构造签名,但不支持直接调用的函数签名(类本身不能像普通函数那样直接执行),因此无法匹配
AccountConstructor中的调用签名要求。
简化实现(无需区分调用方式)
如果不需要区分new调用和直接调用的返回对象差异,可以直接返回统一结构的对象,配合类型断言跳过TS检查:
const Account: AccountConstructor = function(username: string, password: string) { return { username, password }; } as AccountConstructor;
内容的提问来源于stack exchange,提问作者Ngọc Nguyễn
相关产品推荐
相关产品推荐

