typescript - 返回泛型类型的“类型”
问题描述
我有一个不可变的克隆函数:
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
}
}
T
如果没有我所做的修改, Typescript怀疑该函数是否真的返回相同的类型(所以我们必须通过手动确认类型来让它平静下来。
推荐阅读
- java - 如何从静态方法打印非静态方法?
- java - Java 7中两个日期之间的年差
- php - 我的联系表格中的邮件布局有问题
- symfony - 如何在前端使用 datagrid 的导出功能
- c# - 如何创建一个给出指定列名和类型的 sql 表
- python - C++ 特征库中的 argmax() 方法
- javascript - 我无法声明的内容安全政策错误
- scala - 如果异步添加处理程序,则通过 netty 通道丢失的消息
- javascript - 使用 MSAL2 登录后验证服务器上的用户
- shell - MSB4019 使用 Github 操作运行 Xamarin Android 单元测试