javascript 以类型安全的方式检查对象中的属性

sdnqo3pr  于 6个月前  发布在  Java
关注(0)|答案(3)|浏览(76)

代码

const obj = {};
if ('a' in obj) console.log(42);

字符串
不是typescript(没有错误)。我明白为什么会这样了。另外,在TS 2.8.1中,“in”充当类型保护。
但是,有没有一种方法可以检查属性是否存在,但是如果属性没有在obj的接口中定义,则会出错?

interface Obj{
   a: any;
}


我不是在说检查未定义的...

ekqde3dh

ekqde3dh1#

您不会得到错误,因为您使用字符串来检查属性是否存在。
你会得到这样的错误:

interface Obj{
   a: any;
}

const obj: Obj = { a: "test" };

if (obj.b)          // this is not allowed
if ("b" in obj)     // no error because you use string

字符串
如果你想对字符串属性进行类型检查,你可以添加index signatures using this example

ukqbszuj

ukqbszuj2#

下面的handle函数检查假设的服务器响应typesafe-way:

/**
 * A type guard. Checks if given object x has the key.
 */
const has = <K extends string>(
  key: K,
  x: object,
): x is { [key in K]: unknown } => (
  key in x
);

function handle(response: unknown) {
  if (
    typeof response !== 'object'
    || response == null
    || !has('items', response)
    || !has('meta', response)
  ) {
    // TODO: Paste a proper error handling here.
    throw new Error('Invalid response!');
  }

  console.log(response.items);
  console.log(response.meta);
}

字符串
Playground Link。函数has可能应该保存在一个单独的实用程序模块中。

9fkzdhlc

9fkzdhlc3#

您可以在hasOwnProperty周围实现自己的 Package 器函数,它可以进行类型收缩。

function hasOwnProperty<T, K extends PropertyKey>(
    obj: T,
    prop: K
): obj is T & Record<K, unknown> {
    return Object.prototype.hasOwnProperty.call(obj, prop);
}

字符串
我在这里找到了这个解决方案:TypeScript type narrowing not working when looping
使用方法:

const obj = {
    a: "what",
    b: "ever"
} as { a: string }

obj.b // Type error: Property 'b' does not exist on type '{ a: string; }'

if (hasOwnProperty(obj, "b")) {
    // obj is no longer { a: string } but is now
    // of type { a: string } & Record<"b", unknown>
    console.log(obj.b)
}


这种方法的局限性是,你只能得到一个记录与单一的关键字添加,你指定。这可能是罚款为某些需要,但如果你需要一个更通用的解决方案,那么我建议像Zod库,可以验证一个复杂的对象,并给你给予完整的类型:https://github.com/colinhacks/zod

相关问题