分配参数类型后,如何在TypeScript中打印该参数?

时间:2019-04-07 07:22:24

标签: typescript

我有两个文件。我正在使用具有数据类型Person的构造函数导出any类的一个文件。

在第二个文件中,我正在导入Person类,并且具有一个函数,该函数将基于导入的类返回输出字符串。

我的目标是在使用导入的类的第二个文件中打印信息。不幸的是,我只能得到打字稿来打印出函数对象,而不能打印出函数返回的内容。

这是我要导入的文件:

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(),以便返回该函数的内容?

2 个答案:

答案 0 :(得分:0)

您当前正在将字符串传递给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)); 

答案 1 :(得分:0)

如果您使用类型为Person的参数定义函数,则可以确定不能传递类型为string的参数。您的函数期望已经在某个变量中分配了Person类型的实例并对其进行了初始化。 但是,我认为您正在尝试这样做:

function printPerson(firstName: string) {
  const person = new Person({firstName, ...});
  console.log(person.firstName);
}