تخطَّ إلى المحتوى

First Or Default Null (ARCH3078)

هذا المحتوى غير متوفر بلغتك بعد.

Key typescript.performance.first-or-default-null · Severity warning · Category performance

Taking [0] of a filtered array without checking whether it is empty leads to a runtime error when a property is accessed on undefined.

function firstAdminName(users: User[]): string {
const admin = users.filter((u) => u.role === "admin")[0];
return admin.name;
}
function firstAdminName(users: User[]): string {
const admin = users.find((u) => u.role === "admin");
return admin?.name ?? "unknown";
}

Use find and guard the empty case with ?. / ?? before using the result.