MST

星途 面试题库

面试题:TypeScript 回调中 this 类型的基础应用

在 TypeScript 中,定义一个函数 `fetchData`,它接受一个回调函数作为参数。回调函数会在数据获取成功后执行,并且在回调函数内部需要正确处理 `this` 的类型,假设 `this` 指向一个包含 `name` 属性的对象,要求在回调函数中能访问到 `this.name`。请写出完整代码。
11.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface Context {
    name: string;
}

function fetchData(callback: (this: Context) => void) {
    // 模拟数据获取成功
    const context: Context = { name: 'example' };
    callback.call(context);
}

fetchData(function (this: Context) {
    console.log(this.name);
});