谁能告诉我为什么要在 Typescript 中使用接口(interface),它们是什么?
接口(interface)示例:
interface Person {
firstName: string;
lastName: string;
}
class Student {
fullName: string;
constructor(public firstName: string, public lastName: string) {
this.fullName = firstName + " " + lastName;
}
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let student = new Student("John", "Smith");
console.log(greeter(student));
输出:你好,John Smith
没有接口(interface)相同输出的示例:
class Student {
fullName: string;
constructor(firstName: string, lastName: string) {
this.fullName = firstName + " " + lastName;
}
}
function greeter(person : Student) {
return "Hello, " + person.fullName;
}
let student = new Student("John", "Smith");
console.log(greeter(student));
输出:你好,John Smith
为什么接口(interface)在这种特殊情况下有用?我发现很难理解 typescript 中界面的使用。非常感谢任何详细的解释!
最佳答案
JS 是一种松散类型的语言。所以以下是可能的:
var a = new Student();
a.fullName = a.firstName + ' ' + a.lastName
当您定义接口(interface)时,它知道对象的模式是什么,如果您执行该选项,它会给您一个错误。
Typescript 的全部目标是提供编译时警告。如果您的对象具有预定义的结构,则只能实现这一点。这也有助于打字,因为 IDE 可以为您提供有效的建议。
关于javascript - 为什么我应该在 Typescript 中使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53705948/