我是TypeScript的新手。我想在下面的代码中做的就是写入文档“Hello Jonh Lennon”。但是当我run this in the browser(在html页面中)时,它会写出“Hello [object Object]”。我做错了什么?
class Student{
fullname: string;
constructor(public firstName, public lastName) {
this.fullname = firstName + '' + lastName;
}
}
interface IPerson{
firstName: string;
lastName: string;
}
function say(person: IPerson){
return "Hello " + person;
}
var user = new Student("Jonh", "Lennon");
document.write(say(user));
答案 0 :(得分:2)
[object Object]是javascript需要将任何对象强制转换为字符串时的默认行为。对于return "Hello " + person;
,javascript看到+运算符,然后知道它需要person为字符串,以便将其转换。
你想要的是:
function say(person: IPerson){
return "Hello " + person.fullname;
}