Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface as function return type

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

like image 533
Miuid Avatar asked May 14 '26 15:05

Miuid


1 Answers

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:

  • https://www.typescriptlang.org/docs/handbook/2/generics.html
like image 67
zerkms Avatar answered May 17 '26 16:05

zerkms