简体   繁体   中英

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) . 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. So we have to calm it down by manually affirming the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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