typescript - 工作函数,即使它返回错误的类型

标签 typescript

我正在使用 Codepen.io 对 Typescript 进行第一次测试,我不明白为什么在使用接口(interface)声明函数签名和返回类型后,我可以返回不同的类型而不会出现任何错误。

我错过了什么吗?

示例代码:

interface IPerson {
    getFullName: () => void;
}

class Person implements IPerson{

constructor(
    public name: string,
    public surname: string
){}

getFullName() {
    return this.name + ' ' + this.surname;
}

}


let p = new Person('John','Doe');

console.log(p.getFullName());

结果:

John Doe 

问题: 为什么即使我声明了 void 返回类型,“John Doe”(一个字符串)也会注销?

最佳答案

TypeScript 会抛出一个编译错误,像这样:

Type 'string' is not assignable to type 'void'.

但是 Typescript 仍会编译为 Javascript。 JS 本身没有任何类型的概念,因此只会记录值,因为运行时不知道 getFullName() 的返回类型是什么。

如果在出现编译器错误时不进行编译,可以在 tsconfig.json 中设置 noEmitOnError 标志。

关于typescript - 工作函数,即使它返回错误的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534040/

相关文章:

javascript - 尝试让 Cypress、TypeScript 和 IstanbulJS 协同工作

typescript :同一对象的其他属性引用属性类型

Angular 路由参数 'state' 在类型 'NavigationExtras 中不存在

ANGULAR:无法让我的数据显示在我的 HTML 文件上

javascript - Angular2 转义斜线管道

typescript - 我如何告诉 typescript 在 js 中逐字包含一行而不解析它

javascript - 将 Javascript 成员变量转换为 Typescript 成员变量

javascript - Karma - 如何指向 typescript 覆盖的源 map

node.js - Typescript Node.js 最简单的设置不起作用——错误 TS2307 : Cannot find module 'fs'

javascript - angular2中的 `changeDetection: ChangeDetectionStrategy.OnPush`是否只在一个方向上起作用: top->bottom?