Home:ALL Converter>Typescript interface as function return type

Typescript interface as function return type

Ask Time:2018-08-08T08:21:50         Author:Miuid

Json Formatter

new to Typescript here. I got a question about Typescript using interface as a function return type. I got this interface

interface IPerson { 
    name: string,
    age: number
}

If I assign an object to it, it will check the type and reject if type not match. Like

const person: IPerson = { name: 'Tom', age: '26' };

But if I use it as a return type of a function, it seems like it will not check the type

const personJSON = '{ "name": "Jack", "age": "30"}';

const getPersonFromJSON = <IPerson>(json) : IPerson => {
    return JSON.parse(json);
}

console.log(getPersonFromJSON(personJSON));

Looks like the return value willing to accept String to age.

{ name: 'Jack', age: '30' }

Wondering what I did wrong. Many thanks

Author:Miuid,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51737048/typescript-interface-as-function-return-type
yy