typescript - 从对象推断(不扩展类型)属性
问题描述
- 我有一个类型
MrType<T extends boolean>
- 我有一个功能
MrFn(obj?: { lol: boolean }): MrType<typeof obj.lol>
我试图推断lol
提供的对象上的属性(如果提供的话)是true
或false
但是,由于类型变宽,我撞到了墙
type Magic<T> = T extends { lol: infer U } ? U : false;
const trueObj = { lol: true };
const falseObj = { lol: false };
// should pass
const a: Magic<typeof trueObj> = true; // ok
const b: Magic<typeof falseObj> = false; // ok
const c: Magic<{ lol: true }> = true; // ok
const d: Magic<{ lol: false }> = false; // ok
// should fail
const e: Magic<typeof falseObj> = true; // does not fail
const f: Magic<typeof trueObj> = false; // does not fail
const g: Magic<{ lol: false }> = true; // ok (fails)
const h: Magic<{ lol: true }> = false; // ok (fails)
MytrueObj
和falseObj
get 它们的属性推断为boolean
,这意味着 myMagic<T>
无法检测您是否设置true
或false
有没有办法纠正我的解决方案,或者这是 TS 中的限制?
解决方案
你可以在 TypeScript 3.4+ 中使用新的as const
类型断言来做到这一点:
type Magic<T> = T extends { lol: infer U } ? U : false;
const trueObj = { lol: true } as const;
const falseObj = { lol: false } as const;
// should pass
const a: Magic<typeof trueObj> = true; // ok
const b: Magic<typeof falseObj> = false; // ok
const c: Magic<{ lol: true }> = true; // ok
const d: Magic<{ lol: false }> = false; // ok
// should fail
const e: Magic<typeof falseObj> = true; // ok (fails)
const f: Magic<typeof trueObj> = false; // ok (fails)
const g: Magic<{ lol: false }> = true; // ok (fails)
const h: Magic<{ lol: true }> = false; // ok (fails)
推荐阅读
- verilog - 如何创建使用 OPMODE[6:4] = 100 OPMODE[3:2] = 10 OPMODE[1:0] = 00 的乘数?
- python - 在 keras 中使用自定义生成器读取 3D numpy 文件时出现问题
- java - 私人频道不会触发 Slack 事件
- spring-boot - 具有相同参数值的休眠查询与线程睡眠但得到相同的结果虽然数据库更新行值
- c# - ASP.NET 请求中的 async/await 有什么好处?
- excel - Excel - 我希望将行分组在一起并创建这些分组行的表格,以便按特定列对它们进行排序
- xcode - 在 XCode 中归档 React Native 项目时出现未定义符号错误
- odbc - Apache Superset 是否可以使用来自 ODBC 连接的数据?
- html - React Microfronends:如何将身份验证和其他信息从一个前端应用程序传递到另一个前端应用程序?
- logback - 为什么这个 logback 配置不写入任何文件附加器?