[英]Typescript: Property 'name' does not exist on type 'Employee[]'
我對 typescript 完全陌生,我被這個錯誤消息難住了: Property 'name' does not exist on type 'Employee[]'
有人可以指出我沒有在Employee
中應用“name”類型的地方嗎大批? 謝謝。
interface Employee {
id: number;
name: string;
title: string;
}
var employees: Employee[] = [
{ id: 0, name: "Franklin", title: "Software Enginner" },
{ id: 1, name: "Jamie", title: "Human Resources" },
{ id: 2, name: "Henry", title: "Application Designer" },
{ id: 3, name: "Lauren" title: "Software Enginner" },
{ id: 4, name: "Daniel" title: "Software Enginner 2" },
];
function fetchEmployeeName(id : number) {
var employee = employees.filter(
(employee) => employee.id === id
);
// The error occurs when I try to return a "name" under an employee that matched by id.
return employee.name;
}
console.log("Got Employee: "), fetchEmployeeName(3));
嘗試使用 find 而不是 filter。 過濾器返回一個數組。 Find 返回單個 object。 下一次,如果使用 vscode,則 hover 在 fetchEmployeeName 的第一行覆蓋employee,並檢查其類型。 vscode 中的 Intellisense 會向你指出,employee 顯然是一個數組。
filter
返回一個包含所有匹配項的新數組:
[1, 2, 3].filter(i => i === 4)
以上將返回一個空數組。
您要使用的是find
,它將返回單個匹配項或undefined
。
修改fetchEmployeeName
function 以使用find
:
function fetchEmployeeName(id : number): string | null {
var employee = employees.find(
(employee) => employee.id === id
);
if (employee === undefined) return null;
return employee.name;
}
有了它,發生了什么,您的過濾器正在返回一個未定義為 object 的新“員工”,我的建議是始終嘗試使用純函數並了解您的回報是什么
interface Employee {
id: number;
name: string;
title: string;
}
var employees: Employee[] = [
{ id: 0, name: "Franklin", title: "Software Enginner" },
{ id: 1, name: "Jamie", title: "Human Resources" },
{ id: 2, name: "Henry", title: "Application Designer" },
{ id: 3, name: "Lauren", title: "Software Enginner" },
{ id: 4, name: "Daniel", title: "Software Enginner 2" },
];
function fetchEmployeeName (id:number, employees: Employee[]){
let employee = null
for (let i = 0, j = employees.length ; i < j; i++) {
if (employees[i].id === id) {
employee = employees[i].name
}
}
return employee
}
console.log(`Got employee 3: ${fetchEmployeeName(3,employees)}`);
我強烈建議你使用find
而不是filter
,但如果你真的想堅持你的方法,你將不得不通過它的索引訪問 employees 數組中唯一的成員( filter
返回一個填充了滿足指定元素的數組健康)狀況)。 例如:
return employee[0].name
同樣,您可以通過使用filter
來解決這個特定問題,因為它返回您訪問的單個元素而無需索引(這將允許您保留 return 語句原樣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.