JS Built-ins
TypeScriptintermediate

Type Guard β€” parseJSON

πŸ“– Usage Example
function parseJSON<T>(json: string, guard: (x: unknown) => x is T): T | null {
  try { const v = JSON.parse(json); return guard(v) ? v : null }
  catch { return null }
}

Pairing JSON.parse with a type guard validates the parsed data at the TypeScript boundary.

Type Guards: Runtime Validation

Challenge: Implement parseJSON<T>(json: string, guard: (x: unknown) => x is T): T | null β€” parse the JSON and validate it with the guard, returning null on failure.

parseJSON('{"n":1}', (x): x is {n:number} => typeof (x as any).n === 'number')  // β†’ { n: 1 }
parseJSON('bad json', () => true)  // β†’ null
πŸ’‘ Hints (1)
  • β€’ Wrap JSON.parse in a try/catch and apply the guard to the result.