只要看一下这个打字稿代码:
图书馆
interface Human {
name: string;
age: number;
}
export default class HumanFactory {
getHuman(): Human {
return {
name: "John",
age: 22,
}
}
}
Run Code Online (Sandbox Code Playgroud)
索引
import HumanFactory from "./lib";
export class Foo {
human: any;
constructor() {
const factory = new HumanFactory();
this.human = factory.getHuman();
}
diffWithError(age: number): number {
return age - this.human.name;
}
diffWithTypingAndAutocoplete(age: number): number {
const factory = new HumanFactory();
return age - factory.getHuman().name;
}
}
Run Code Online (Sandbox Code Playgroud)
“ Foo”类的“人”属性中的问题。我无法从lib.ts中将此变量的类型定义为“人机”接口。
在方法“ diffWithError”中,我犯了一个错误-在算术运算中使用数字“ age”和字符串“ name”,但是IDE和ts编译器都不知道这一点,因为在这种情况下,“ this.human.name”的类型为“任何” …