还要注意的是,在构造函数的参数上使用public等同于创建了同名的成员变量。
注:public修饰符会引发
Parameter 'firstName' implicitly has an 'any' type.
,解决方法是在tsconfig.json
文件中,添加"noImplicitAny": false
,或者将"strict": true
,改为"strict": false
// src/04student.ts
class Student {
fullName: string;
// public 等同于创建了同名的成员变量
// constructor (public firstName: string, public lastName: string) {
// this.fullName = this.firstName + this.lastName
// }
firstName: string; // 成员变量
lastName: string// 成员变量
constructor (firstName: string, lastName: string) {
this.firstName = firstName
this.lastName = lastName
this.fullName = this.firstName + this.lastName
}
}
interface IPerson {
firstName: string
lastName: string
}
function greeter2 (user: IPerson): string {
return 'hello' + user.firstName + user.lastName
}
const stu = new Student('成', '三岁')
console.log(greeter2(stu))