I need to use a Typescript interface as a function return type. The interface is
interface IPerson {
name: string,
age: number
}
If I assign an object to it, it checks the type and rejects if it doesn't 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 doesn't 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 accepts age as String.
{ name: 'Jack', age: '30' }
Wondering what I did wrong. Many thanks
const getPersonFromJSON = <IPerson>(json) : IPerson => {
return JSON.parse(json);
}
this is identical to
const getPersonFromJSON = <T>(json) : T => {
return JSON.parse(json);
}
and defines a generic function. So effectively it's <any>(json: any): any
You should declare it as
const getPersonFromJSON = (json) : IPerson => {
return JSON.parse(json);
}
instead.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With