如何调整MapToInput泛型,避免匹配仅null/undefined的字段?
解决方案
修改后的泛型类型定义如下:
export type MapToInput<T> = { [K in keyof T]: firestore.Timestamp extends T[K] ? firestore.Timestamp | Date : T[K]; };
原理说明
原泛型的判断逻辑T[K] extends firestore.Timestamp | undefined | null会误匹配仅含undefined、null或null | undefined的类型。
新条件firestore.Timestamp extends T[K]的核心逻辑是:仅当字段类型本身包含firestore.Timestamp时,才执行类型转换:
- 对于
firestore.Timestamp、firestore.Timestamp | undefined、firestore.Timestamp | null、firestore.Timestamp | undefined | null这些目标类型,firestore.Timestamp可以赋值给它们,条件为true,触发转换。 - 对于仅
undefined、仅null或null | undefined的类型,firestore.Timestamp无法赋值给它们,条件为false,保留原类型。
场景验证
场景1:纯Timestamp类型
interface Beep { a: firestore.Timestamp; } type y = MapToInput<Beep>; // y.a 类型为 firestore.Timestamp | Date(符合预期)
场景2:可选Timestamp类型
interface Blab { a?: firestore.Timestamp; } type z = MapToInput<Blab>; // z.a 类型为 firestore.Timestamp | Date | undefined(符合预期)
仅Undefined类型(需排除的场景)
interface Boop { a: undefined; } type x = MapToInput<Boop>; // x.a 类型仍为 undefined(符合预期)
边缘场景验证
- 仅Null类型:
interface BoopNull { a: null; } type xNull = MapToInput<BoopNull>; // xNull.a 类型仍为 null(符合预期)
- Null + Undefined类型:
interface BoopNullUndefined { a: null | undefined; } type xNU = MapToInput<BoopNullUndefined>; // xNU.a 类型仍为 null | undefined(符合预期)
- Timestamp + Null类型:
interface BeepNull { a: firestore.Timestamp | null; } type yNull = MapToInput<BeepNull>; // yNull.a 类型为 firestore.Timestamp | Date | null(符合预期)
内容的提问来源于stack exchange,提问作者albertjan
相关产品推荐
相关产品推荐

