打字稿以类型安全的方式检查对象中的属性

问题描述 投票:0回答:3

代码

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

不是打字稿(没有错误)。我明白为什么会这样。此外,在 TS 2.8.1 中,“in”充当类型保护。

但是,有没有一种方法可以检查属性是否存在,但如果该属性没有在 obj 的接口中定义,则会出错?

interface Obj{
   a: any;
}

我不是在谈论检查未定义...

javascript typescript types undefined typeguards
3个回答
31
投票

您不会收到错误,因为您使用字符串来检查属性是否存在。

你会这样得到错误:

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

如果您希望类型检查适用于字符串属性,您可以使用此示例添加索引签名


12
投票

以下

handle
函数检查假设的服务器响应类型安全方式:

/**
 * 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);
}

游乐场链接。函数

has
可能应该保存在单独的实用程序模块中。


7
投票

您可以围绕 hasOwnProperty 实现自己的包装函数,以缩小类型范围。

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

我在这里找到了这个解决方案: TypeScript 类型缩小在循环时不起作用

用途:

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

© www.soinside.com 2019 - 2024. All rights reserved.