gpt4 book ai didi

arrays - typescript 告诉我方法是属性并且不能创建对象

转载 作者:行者123 更新时间:2023-12-01 08:18:12 24 4
gpt4 key购买 nike

我是 typescript 的新手,不了解以下行为。我有一个这样的界面:

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

/**
* Representing a Person
*/
export interface Person{
id: number;
title: Titles
firstName: string;
lastName: string;
getName(): string;
}
现在我想创建一个常量数组来模拟一些员工。因此我得到了这个类:
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" }
];
预编译器告诉我这是行不通的,因为在我的示例值中没有声明 Property getName。但这是一个我只想初始化一些 Persons 来填充数组的方法。

The Type "({ id: number; title: Titles.Nothing; firstName: string; lastName: string; } | { id: number; titl..." cannot be assigned to "Employee[]".

The Property "getName" is missed in Type "{ id: number; title: Titles.Nothing; firstName: string; lastName: string; }".


有人可以帮忙吗?我敢肯定这很愚蠢,但我坚持。

最佳答案

问题是对象字面量不是类 Employee 的实例。 .为了创建 Employee 的实例您需要使用 new运算符 (new Employee())。

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

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

更好的选择是提供一个接受对象字面量作为参数的构造函数,并使用:
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

关于arrays - typescript 告诉我方法是属性并且不能创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com