首页 > 解决方案 > 返回泛型类型的“类型”

问题描述

我有一个不可变的克隆函数:

import { isObject, toPairs } from 'lodash';

export function cloneDeepWithoutUndefinedKeys<T>(o: T): any {
    if (Array.isArray(o)) {
        return o.map((el) => cloneDeepWithoutUndefinedKeys(el));
    } else if (isObject(o)) {
        const c: { [key: string]: any } = {};
        for (const [key, value] of toPairs(o as { [key: string]: any })) {
            if (value === undefined) {
                continue;
            }
            c[key] = cloneDeepWithoutUndefinedKeys(value);
        }
        return c;
    } else {
        return o;
    }
}

我必须做的函数的返回,any但我希望它是sameTypeOf(T)。这可能吗?

标签: typescript

解决方案


我会用这个。

export function cloneDeepWithoutUndefinedKeys<T extends any>(o: T): T {
    if (Array.isArray(o)) {
        return (o.map((el: any) => cloneDeepWithoutUndefinedKeys(el))) as T; // ADDED
    } else if (isObject(o)) {
        const c: { [key: string]: any } = {};
        for (const [key, value] of toPairs(o)) {
            if (value === undefined) {
                continue;
            }
            c[key] = cloneDeepWithoutUndefinedKeys(value);
        }
        return c as T; // ADDED
    } else {
      return o
    }
}

T如果没有我所做的修改, Typescript怀疑该函数是否真的返回相同的类型(所以我们必须通过手动确认类型来让它平静下来。


推荐阅读