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

TypeScript函数中显式this:<type>的正确实现方式咨询

问题分析与解决

你的核心问题在于:TypeScript里的this: User只是类型标注,它只负责告诉TypeScript编译器回调函数内的this应该是什么类型,并不会自动帮你在运行时把this绑定到User实例上。而你用users.filter(filter)调用回调时,Array.prototype.filter的回调函数默认不会把遍历的元素作为this传入(严格模式下this是undefined),所以才会出现this.admin取不到值的情况。

正确实现方式

要让this: User的机制生效,你需要在调用回调函数时,手动把当前遍历的User实例绑定为回调的this。修改filterUsers方法如下:

type User = {
  id: number;
  admin: boolean;
}

interface DB {
  filterUsers(filter: (this: User) => boolean): User[];
}

const users: User[] = [
    { id: 1, admin: true },
    { id: 2, admin: false },
  ];

const db: DB = {
  filterUsers(filter: (this: User) => boolean) {
    const matchedUsers: User[] = [];
    // 手动遍历每个user,用call把user绑定为回调的this
    for (const user of users) {
      if (filter.call(user)) {
        matchedUsers.push(user);
      }
    }
    return matchedUsers;
  }
};

const admins = db.filterUsers(function (this: User) {
  return this.admin;
});

console.log(admins); // 输出: [{ id: 1, admin: true }]

为什么这样能生效?

  • TypeScript的this: User标注确保了编译时的类型检查,你在回调里访问this.admin不会有类型错误;
  • 运行时通过filter.call(user),把当前遍历的User实例作为this传给回调函数,符合JS的this绑定规则,此时回调里的this就确实指向User实例了。

补充实现方式

如果你不想手动遍历,也可以用Array.prototype.reduce来实现,本质还是手动绑定this:

filterUsers(filter: (this: User) => boolean) {
  return users.reduce((acc, user) => {
    if (filter.call(user)) {
      acc.push(user);
    }
    return acc;
  }, [] as User[]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 01:55:56