javascript - Typescript: อาร์กิวเมนต์ประเภท 'string | undefined' ไม่สามารถกำหนดให้กับพารามิเตอร์ประเภท 'string' ได้
ฉันมีรายการของลิสต์อาร์เรย์ซ้อนกัน ฉันกำลังพยายามกรองตามค่าของอาร์เรย์ เมื่อฉันกรองจะเกิดข้อผิดพลาด ฉันกำลังใช้ TypeScript กับ ESLint
Argument of type 'string | undefined' is not assignable to parameter of type 'string'
แต่ฉันได้ตรวจสอบค่าที่เป็น null/undefined แล้ว แต่ฉันยังคงได้รับข้อผิดพลาดอยู่
interface User {
id: string;
username?: string;
}
function getList (user:User){
if(user.username === undefined){
return {};
}
let arrayData: string[][] = [];
arrayData = [["abcd"],["efgh"],["xyz"],["abcd","xyz"]];
//here i have differnt logic
const filterData = arrayData.filter(list => list.includes(user.username));
return filterData;
}
getList({id: "123", username: "xyz"});
เมื่อฉันใช้ non-null assertion operator ข้อผิดพลาดก็ถูกแก้ไข แต่เกิดปัญหา lint
const filterData = arrayData.filter(list => list.includes(user.username!));
ใครช่วยฉันแก้ปัญหานี้ได้ไหม
คำตอบ #1
คุณกำลังเปรียบเทียบ User .username ซึ่งเป็น Optional ซึ่งหมายความว่ามีชนิดเป็น string | undefined กับทุก string ในอาเรย์
คุณสามารถเปลี่ยนประเภทของอาเรย์ของคุณได้เป็น: arrayData: Array<Array<string|undefined>> หรือคุณสามารถใช้ as เพื่อตีความมันเป็น string แทนที่จะเป็น string|undefined: เช่น: list.includes(user.username as string)
คำตอบ #2
คุณสามารถประกาศชื่อผู้ใช้ได้ดังนี้:
username?: string | undefined;