我有两个文件。我正在导出Person
类的一个文件,其构造函数的数据类型为any
。
在第二个文件中,我正在导入Person
类,并且我有一个函数,它根据导入的类返回输出字符串。
我的目标是在第二个文件中打印信息,该文件使用了导入的类。不幸的是,我只能获取打印函数对象的typescript而不是函数返回的内容。
这是我导入的文件:
export class Person {
firstName: string;
middleName: string;
lastName: string;
constructor(data?: any) {
this.firstName = data.firstName || 'Jake';
this.lastName = data.lastName || 'Jeffries';
this.middleName = data.middleName;
}
}
这是我试图从以下结果得到的文件:
import { Person } from './person.model';
function printPerson(person: Person) {
return `This should print along with the first name of person type,
${person.firstName}!`
}
console.log(printPerson("Jacob"));
这应打印出来:
"This should print along with the first name of person type,Jacob"
但我得到错误:
“Jacob类型的参数不能赋予'Person'类型的参数”。
如果我只是尝试控制台记录printPerson()
,那么我只得到打印出来的函数对象,而不是函数内部的消息。
我的问题是,什么参数对printPerson()
有效,以便我得到该函数中的内容的返回?
您当前正在将字符串传递给printPerson()
函数。 printPerson()
函数期望第一个参数是Person
类的实例。
请考虑进行以下更改以解决此问题:
import { Person } from './person.model';
function printPerson(person: Person) {
return `This should print along with the first name of person type,
${person.firstName}!`
}
/* Create a person instance */
const jacobPerson = new Person({
firstName : 'Jacob',
lastName : 'Smith',
middleName : 'E'
});
/* Pass the person instance to printPerson() */
console.log(printPerson(jacobPerson));
如果使用Person
类型的参数定义函数,那么肯定无法传递类型为string
的参数。您的函数期望已经在某个变量中分配并初始化了Person
类型的实例。但是,我认为您正在尝试这样做:
function printPerson(firstName: string) {
const person = new Person({firstName, ...});
console.log(person.firstName);
}