typescript - 我应该如何处理空对象的类型?
问题描述
我的值要么是{}
,要么是具有 30 个字段的对象。ESLint 建议前一种情况的合理类型是Record<string, never>
,所以复合类型看起来像Record<string, never> | MyBigObjectType
。
我正在尝试使用 field 的存在与否来区分这两种情况Foo
。不幸的是,我不能使用"Foo" in val
or!!val.Foo
因为类型检查器认为它可能存在于Record<string, never>
. 但它不能!这就是整个目的never
!
我如何在没有类型转换的情况下完成此操作?
解决方案
You haven't shared how you're creating or using these objects, but if using an assertion (cast) is specifically the problem, you can use a function returning a type predicate for compile-time and runtime safety.
// "an object with 30 fields"
type MyBigObjectType = {
foo: string;
bar: number;
// etc...
};
function isMyObject (value: object): value is MyBigObjectType {
// checking specified size of keys and presence of 'foo' property,
// but you can modify to fit your requirements
return Object.keys(value).length === 30 && 'foo' in value;
}
function fn (value: MyBigObjectType): void {}
const o1 = {};
fn(o1); // nope
if (isMyObject(o1)) fn(o1); // ok
declare const o2: object;
fn(o2); // nope
if (isMyObject(o2)) fn(o2); // ok
declare const o3: MyBigObjectType;
fn(o3); // ok
推荐阅读
- javascript - Sequelize,在创建的响应中包含关系的数据
- audio - SoX 归一化和峰值检测
- sql - 如何为唯一 id 组合返回更大的周期值?
- java - 在 DocDoku 中加载示例数据时出错
- java - Android 应用程序中的后台位置更新。(用于实时位置跟踪)
- r - R:如何停止在绘图图表上将百分比四舍五入到小数点后 0 位?
- reactjs - 我正在尝试运行命令 make start。但我收到以下错误
- reactjs - 做出反应。循环功能,不知道如何停止。在函数中映射和获取
- javascript - 如何使用 ID 而不是类添加或删除?
- c# - R中基于命令行参数的操作