简体   繁体   English

返回通用类型的“类型”

[英]Return “type” of generic type

I have a immutable clone function: 我有一个不变的克隆函数:

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

The return of the function I had to make it any but I want it to be sameTypeOf(T) . 该函数的返回值我必须使其成为any函数,但我希望它是sameTypeOf(T) Is this possible? 这可能吗?

I'd use this. 我会用这个。

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

Without the modifications I made, Typescript doubts that the function really returns the same type ( T ), but it is not smart enough to infer that it's really of the same type, basically. 如果没有我所做的修改,Typescript会怀疑该函数是否确实返回相同的类型( T ),但是基本上不能推断出它确实是同一类型。 So we have to calm it down by manually affirming the type. 因此,我们必须通过手动确认类型来使其平静下来。

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

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