Why does TypesScript miss a mistake at the password json stage?



  • Example of code:

    
    type MyType  = {
        id:number,
        page:number,
    

    }
    const j = {"id": "1", "page": "2"}
    const a:MyType = JSON.parse(j)

    console.log(typeof a.id, parseInt(a.id,10), a.id)

    As a result of steaming json line, all numbers are stringbut also variable a type assigned id as specified number♪ Why is ts not fighting on this line, but making a mistake when I want to do it? parseInt(a.id,10)

    https://www.typescriptlang.org/play?ts=4.4.0-beta&ssl=10&ssc=1&pln=1&pc=1#code/C4TwDgpgBAsiAq5pQLxQN4FgBQU9QEsATALgDsBXAWwCMIAnAGh3yjAEMBzCc6upnDgC%20OAMYB7MgGdgUAFaooAA3QAiYqpJRVARlWNtHbpu0AmVUKVjJMqOxJxEkRQCkAygHkAcgDoO9KQgACjkASihBbAlpcQAbCB9Y8U4g0EhxADM7H2IDf0CASTJgIPYcokYdAAZQgzLiUJwgA



  • If you want a safe solution, you need your own function to check JSON and remove the type. typescript I don't know how to make it.

    type MyType = {
        id: number,
        page: number,
    

    }
    const j1 = { "id": "1", "page": "2" };
    const j2 = { "id": 1, "page": 2 };

    // Эта функция говорит typescript, что в случае true переданный аргумент имеет тип MyType.
    const isMyType = (json: any): json is MyType => {
    const values = Object.values(json);
    for(let i = 0; i < values.length; i++) {
    if (typeof values[i] !== 'number') {
    return false;
    }
    }

    return true;
    

    }

    const a = JSON.parse(j1);
    const b = JSON.parse(j2);

    if (isMyType(a)) {
    console.log(a); // не выведется.
    }

    if (isMyType(b)) {
    console.log(b); // выведется и тип будет равен MyType.
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2