Typescript告诉我方法是属性而不能创建Object

时间:2018-06-06 07:57:57

标签: arrays typescript

我是打字稿的新手,并不了解以下行为。我有这样的界面:

import { Titles } from "../enumerations/titles";

/**
 * Representing a Person
 */
export interface Person{
    id: number;
    title: Titles
    firstName: string;
    lastName: string;
    getName(): string;
}

现在我想创建一个Const数组来模拟一些Employees。所以我上了这堂课:

import { Person } from "../interfaces/person";
import { Titles } from "../enumerations/titles";

/**
 * Represents an Employee
 */
export class Employee implements Person{
    id: number;
    title: Titles
    firstName: string;
    lastName: string;

    getName(): string {

        if (this.title === Titles.Nothing){
            return this.firstName + " " + this.lastName;
        }

        return this.title + " " + this.firstName + " " + this.lastName;        
    }
}

和常数:

import { Titles } from "../enumerations/titles";
import { Person } from "../interfaces/person";

export const PROJECTMANAGER: Employee[] = [
    { id: 1, title: Titles.Nothing, firstName: "Max", lastName: "Mustermann" },
    { id: 2, title: Titles.Nothing, firstName: "Willy", lastName: "Brandt" },
    { id: 3, title: Titles.Dr, firstName: "Walter", lastName: "Steinmeier" }
];

预编译器告诉我这不起作用,因为我的示例值中没有声明属性getName。但这是一个方法我只想初始化一些人来填充数组。

  

类型“({id:number; title:Titles.Nothing; firstName:string; lastName:string;} | {id:number; titl ...”无法分配给“Employee []”。

     

在类型“{id:number; title:Titles.Nothing; firstName:string; lastName:string;}”中遗漏了属性“getName”。

有人可以帮忙吗?我确定这很愚蠢,但我一直在坚持。

2 个答案:

答案 0 :(得分:2)

问题是对象文字不是类Employee的实例。要创建new的实例,您需要使用new Employee()运算符(let emp: Employee = { id: 1, title: Titles.Nothing, firstName: "Max", lastName: "Mustermann", getName : Employee.prototype.getName } // This is ok, we have the getName member console.log(emp instanceof Employee) /// Still false, not an instance since we did not create it using new Employee )。

由于typescript使用结构兼容性来确定类型兼容性,因此如果提供类的所有成员,则可以分配对象文字。但是对象文字仍然不是该类的实例:

export class Employee implements Person{
    constructor (data: Partial<Employee>) {
        Object.assign(this, data);
    }
    /// ....
}


let emp: Employee =  new Employee({ 
    id: 1, title: Titles.Nothing, firstName: "Max", lastName: "Mustermann",
});

console.log(emp instanceof Employee) /// True now

更好的选择是提供一个接受对象文字作为参数的构造函数:

{{1}}

答案 1 :(得分:1)

由于Employee是一个类,而不是一个简单的对象,因此您需要使用Employee创建新的new,而不是使用简单的对象声明。

定义一个以idtitlefirstNamelastName为参数的构造函数,然后执行以下操作:

export const PROJECTMANAGER: Employee[] = [
    new Employee(1, Titles.Nothing, "Max", "Mustermann"),
    new Employee(2, Titles.Nothing, "Willy", "Brandt"),
    new Employee(3, Titles.Dr, "Walter", "Steinmeier")
];