MST

星途 面试题库

面试题:TypeScript中this类型注解在函数重载与泛型结合场景下的应用

编写一个TypeScript函数,它既支持函数重载,又使用泛型,且在函数内部需要正确注解this类型。函数功能是根据传入的参数类型不同,返回不同处理后的结果,同时在函数内部可能会访问到对象的一些属性,要保证this类型注解的正确性,避免运行时错误。
50.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
class MyClass {
    private myProperty: string;
    constructor(property: string) {
        this.myProperty = property;
    }

    // 函数重载声明
    myFunction<T extends string>(arg: T): T;
    myFunction<T extends number>(arg: T): T;
    myFunction<T>(arg: T): T {
        // 正确注解this类型
        const self = this as MyClass;
        if (typeof arg ==='string') {
            // 这里可以根据对象属性进行处理,例如结合this.myProperty
            return arg + self.myProperty as unknown as T;
        } else if (typeof arg === 'number') {
            // 同样可以根据对象属性处理
            return arg + Number(self.myProperty) as unknown as T;
        }
        return arg;
    }
}

使用示例:

const instance = new MyClass('suffix');
const result1 = instance.myFunction('prefix');
const result2 = instance.myFunction(10);