首页 > 解决方案 > 如何更好地处理部分接口

问题描述

在下面的场景中,我不想信任不受信任的对象,并且想在对其进行操作之前检查每个字段是否真实。但是,使用 Partial 泛型时,它不会在尝试将字段传递给函数时推断该字段不是未定义的。有没有更好的方法来处理这个?

export interface IFoo {
  id: number;
  value: string;
}

export function DoBar(obj: IFoo) {
  // do stuff
  return;
}

const untrustedObj: Partial<IFoo> = { id: 1, value: 'test' };

if (untrustedObj.id && untrustedObj.value) {
  DoBar(untrustedObj); // Error
}

错误:

Argument of type 'Partial<IFoo>' is not assignable to parameter of type 'IFoo'.
  Types of property 'id' are incompatible.
    Type 'number | undefined' is not assignable to type 'number'.
      Type 'undefined' is not assignable to type 'number'.ts(2345)

标签: typescript

解决方案


您可以编写一个类型保护函数is缩小对象的类型:

function hasKey<T, K extends keyof T>(obj: Partial<T>, key: K):
    obj is Partial<T> & { [k in K]: T[k] }
{
    return Object.prototype.hasOwnProperty.call(obj, key);
}

用法:

if(hasKey(untrustedObj, 'id') && hasKey(untrustedObj, 'value')) {
  doBar(untrustedObj); // no type error
}

我已将其用作Object.prototype.hasOwnProperty测试此问题的更通用解决方案,因为您可能想要检查布尔属性是否存在(而不是检查它是否为真)。

游乐场链接


推荐阅读