TypeScript: variable type for "dynamic value" assigning?

Viewed 389

In TypeScript, I can catch error from the following script.

let num: number = 1;
num = 'abc';

But the following script can be executed without error:

let num: number = 1;
let s = '{"a":"abc"}';
let j = JSON.parse(s);
num = j.a; // assigning a string "abc"

So what's the correct way to catch error from the second script.

2 Answers

You need to cast your JSON using an interface because the return value of JSON.parse is of type any.

interface JSON {
    /**
      * Converts a JavaScript Object Notation (JSON) string into an object.
      * @param text A valid JSON string.
      * @param reviver A function that transforms the results. This function is called for each member of the object.
      * If a member contains nested objects, the nested objects are transformed before the parent object is.
      */
    parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
}
let num: number = 1;
let s = '{"a":"abc"}';
let _j = JSON.parse(s);
interface MyJSON {
  [key: string]: number
}
let j = _j as MyJSON
num = j.a;

TypeScript applies type rules at compile time, not runtime. TypeScript does not have access to runtime values (it doesn't even exist at runtime; it gets compiled down to JavaScript). If you want to validate data (such as JSON), you need a runtime validator, not types. For example, see JSON Schema.

Related