TypeScript中如何从生成的类型定义里剔除所有never类型属性
TypeScript 剔除类型中never属性的解决方案
直接使用支持键重映射的工具泛型即可实现需求:
步骤1:定义通用剔除never属性的工具类型
// TS 4.1及以上版本可用 type RemoveNeverProperties<T> = { [K in keyof T as T[K] extends never ? never : K]: T[K] }
如果需要兼容TS4.1以下版本,可以用Pick实现:
// 兼容低版本TS的写法 type RemoveNeverProperties<T> = Pick<T, { [K in keyof T]: T[K] extends never ? never : K }[keyof T]>
步骤2:改造原有泛型
将你定义的MapForeignKeys泛型的输出套入上面的工具类型即可:
type MapForeignKeys<TExpandMap extends expandMap, TForeignKeys> = RemoveNeverProperties<{ [Prop in keyof TExpandMap]: TExpandMap[Prop] extends { association: 'belongsTo', instance: BaseModel, foreignKey: any } ? TExpandMap[Prop]['instance']['_creationAttributes'] | TExpandMap[Prop]['instance'] | TForeignKeys[TExpandMap[Prop]['foreignKey']] : never }>
实现原理
- 原生映射类型仅会将不符合条件的属性值设为
never,不会自动删除对应的属性键,因此会残留无效的never属性。 - 上面的工具类型通过条件判断,将值为
never的属性的键也映射为never,TS会自动过滤联合类型中的never项,最终只保留值符合要求的属性。
内容的提问来源于stack exchange,提问作者Adam Baranyai
相关产品推荐
相关产品推荐

