Typescript 接口作为函数返回类型

Miu*_*uid 3 casting typescript

这里是 Typescript 的新手。我有一个关于 Typescript 使用接口作为函数返回类型的问题。我得到了这个界面

interface IPerson { 
    name: string,
    age: number
}
Run Code Online (Sandbox Code Playgroud)

如果我为其分配一个对象,它将检查类型并在类型不匹配时拒绝。喜欢

const person: IPerson = { name: 'Tom', age: '26' };
Run Code Online (Sandbox Code Playgroud)

但是如果我将它用作函数的返回类型,它似乎不会检查类型

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

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

console.log(getPersonFromJSON(personJSON));
Run Code Online (Sandbox Code Playgroud)

看起来像愿意接受 String 年龄的返回值。

{ name: 'Jack', age: '30' }
Run Code Online (Sandbox Code Playgroud)

想知道我做错了什么。非常感谢

zer*_*kms 7

const getPersonFromJSON = <IPerson>(json) : IPerson => {
    return JSON.parse(json);
}
Run Code Online (Sandbox Code Playgroud)

这与

const getPersonFromJSON = <T>(json) : T => {
    return JSON.parse(json);
}
Run Code Online (Sandbox Code Playgroud)

并定义了一个泛型函数。如此有效<any>(json: any): any

你应该把它声明为

const getPersonFromJSON = (json) : IPerson => {
    return JSON.parse(json);
}
Run Code Online (Sandbox Code Playgroud)

反而。

参考: