You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建仅允许普通函数而非箭头函数的TypeScript类型?

如何在TypeScript中禁止为指定属性赋值箭头函数

要实现这个需求,核心是利用普通函数与箭头函数的类型差异:普通函数拥有prototype属性,箭头函数没有。我们可以通过条件类型约束目标属性必须是带有prototype的普通函数,从而在赋值箭头函数时直接触发编译错误。

实现步骤

  1. 定义辅助类型筛选普通函数
// 仅允许拥有prototype的普通函数,自动排除箭头函数
type OrdinaryFunction<T extends (...args: any[]) => any> = 
  T extends { prototype: any } ? T : never;
  1. 修改目标对象类型,用辅助类型约束指定属性
class MyClass {
  constructor(public firstName: string, public lastName: string, private effect: Effect) {}

  doThing() {
    // 通过call()修改specialFunc的this指向
    this.effect.specialFunc.call(this, 5, 7);
  }
}

type Effect = {
  irrelevantProp?: any;
  irrelevantProp2?: any;
  // 约束specialFunc必须是带指定this参数的普通函数
  specialFunc: OrdinaryFunction<(
    this: Pick<MyClass, 'firstName' | 'lastName'>, 
    a: number, 
    b: number
  ) => string>;
}

测试验证

// ✅ 合法:普通函数表达式
const effectNormal: Effect = {
  specialFunc(a, b) {
    console.log(this.firstName);
    console.log(this.lastName);
    return 'blabla';
  },
}

// ✅ 合法:函数声明式赋值
const effectNormal2: Effect = {
  specialFunc: function(a, b) {
    console.log(this.firstName);
    console.log(this.lastName);
    return 'hello';
  },
}

// ❌ 编译报错:箭头函数无法赋值给never类型
const effectArrow: Effect = {
  specialFunc: (a, b) => {
    console.log(this.firstName);
    console.log(this.lastName);
    return 'whatever';
  }
}

原理说明

当尝试给specialFunc赋值箭头函数时,OrdinaryFunction会检查该函数是否拥有prototype属性。箭头函数的类型不包含prototype,因此条件类型返回never,导致赋值时类型不匹配,直接触发编译错误。而普通函数拥有prototype,条件类型会返回原函数类型,因此可以正常赋值。

内容的提问来源于stack exchange,提问作者Nkemdi Anyiam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:20:34