首页 > 解决方案 > 我应该如何处理空对象的类型?

问题描述

我的值要么是{},要么是具有 30 个字段的对象。ESLint 建议前一种情况的合理类型是Record<string, never>,所以复合类型看起来像Record<string, never> | MyBigObjectType

我正在尝试使用 field 的存在与否来区分这两种情况Foo。不幸的是,我不能使用"Foo" in valor!!val.Foo因为类型检查器认为它可能存在于Record<string, never>. 但它不能!这就是整个目的never

我如何在没有类型转换的情况下完成此操作?

标签: typescript

解决方案


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.

TS Playground link

// "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

推荐阅读