简体   繁体   中英

Typescript interface as function return type

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM