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

时间:2018-04-07 12:20:01

标签: javascript typescript types undefined

代码

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

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

但是,有没有办法检查属性是否存在,但如果在obj的接口中没有定义属性,则会出错?

interface Obj{
   a: any;
}

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

2 个答案:

答案 0 :(得分:5)

以下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);
}

Playground Link。函数has应该保留在单独的实用程序模块中。

答案 1 :(得分:3)

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

您将以这种方式得到错误:

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