MST
星途 面试题库

面试题:TypeScript交叉类型在复杂场景中的应用

假设你正在开发一个插件系统,有多个插件接口,如`IPlugin1`具有`method1(): void`和`event1: (callback: () => void) => void`,`IPlugin2`具有`method2(): number`和`event2: (callback: (result: number) => void) => void`等。现在需要实现一个函数`combinePlugins`,它接收一个由这些插件接口交叉类型组成的数组作为参数,遍历这个数组,依次调用每个插件的方法并注册事件,最后返回一个包含所有插件调用结果的对象。请用TypeScript实现该功能,并处理可能出现的类型兼容性和错误情况。
46.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface IPlugin1 {
    method1(): void;
    event1: (callback: () => void) => void;
}

interface IPlugin2 {
    method2(): number;
    event2: (callback: (result: number) => void) => void;
}

type CombinedPlugin = IPlugin1 & IPlugin2;

function combinePlugins(plugins: CombinedPlugin[]): { [key: string]: any } {
    const results: { [key: string]: any } = {};

    plugins.forEach((plugin, index) => {
        try {
            if ('method1' in plugin) {
                plugin.method1();
                results[`plugin${index + 1}_method1`] = 'Successfully called method1';
            }
            if ('method2' in plugin) {
                const method2Result = plugin.method2();
                results[`plugin${index + 1}_method2`] = method2Result;
            }
            if ('event1' in plugin) {
                plugin.event1(() => {
                    results[`plugin${index + 1}_event1`] = 'Event1 callback executed';
                });
            }
            if ('event2' in plugin) {
                plugin.event2((result) => {
                    results[`plugin${index + 1}_event2`] = `Event2 callback executed with result: ${result}`;
                });
            }
        } catch (error) {
            results[`plugin${index + 1}_error`] = `Error in plugin ${index + 1}: ${error.message}`;
        }
    });

    return results;
}