繁体   English   中英

返回通用类型的“类型”

[英]Return “type” of generic type

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

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) 这可能吗?

我会用这个。

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
    }
}

如果没有我所做的修改,Typescript会怀疑该函数是否确实返回相同的类型( T ),但是基本上不能推断出它确实是同一类型。 因此,我们必须通过手动确认类型来使其平静下来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM