MST
星途 面试题库

面试题:TypeScript类型断言与联合类型的复杂处理

有一个联合类型`type MixedType = string | number | { value: string };` 编写一个函数,接受`MixedType`类型的参数,使用类型断言和类型守卫来处理不同类型的参数情况。若为字符串,返回字符串的首字母大写形式;若为数字,返回其两倍值;若为对象,返回对象`value`属性值的长度。
41.3万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function handleMixedType(input: MixedType): string | number {
    if (typeof input ==='string') {
        return input.charAt(0).toUpperCase() + input.slice(1);
    } else if (typeof input === 'number') {
        return input * 2;
    } else if ('value' in input) {
        return input.value.length;
    }
    throw new Error('Unsupported type');
}