0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

unknown な値が interface を満たしているか調べる関数を書く

0
Posted at

ajv を使え。

ajv を導入するほどでもないかなというときは object かどうかを確認する関数だけ定義しておくと便利です。

const isObject = (d: unknown): d is Record<keyof any, unknown> =>
  'object' === typeof d && !Array.isArray(d) && !!d

interface Account {
  readonly id: string
  name: string
}

const isAccount = (x: unknown): x is Account =>
  isObject(x) && 'string' === typeof x.id && 'string' === typeof x.name

使用例

for (const txt of [
  '{"id":"qwer","name":"taro"}',
  'null',
  '{}',
]) {
  const a: unknown = JSON.parse(txt) 
  if (isAccount(a)) {
    console.log('ok', a.id, a.name)
  } else {
    console.log('err')
  }
}
// ok qwer taro
// err
// err
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?