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