类型注解
function greeter(person: string) {
return "Hello, " + person;
}
接口
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
类
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
注意
这里的类和 ES6 的类有些许差别
- 支持在 constructor 外定义属性
- 在 constructor 定义的 public 属性会自动成为该类的公有属性(这里还可以为 private、protected)
所以这里的 Student 在实例化成 user 后拥有 4 个属性如下
user; // {fulName: "Jane M. User", firstName: "Jane", middleInitial: "M.", lastName: "User"}