我正在使用 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/