简体   繁体   English

Typescript 接口作为函数返回类型

[英]Typescript interface as function return type

new to Typescript here.这里是 Typescript 的新手。 I got a question about Typescript using interface as a function return type.我有一个关于 Typescript 使用接口作为函数返回类型的问题。 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.看起来返回值愿意接受 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如此有效的是<any>(json: any): any

You should declare it as你应该把它声明为

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

instead.反而。

References:参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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