המשתנה 'test' משומש לפני שהוקצה לו ערך - Typescript


אני מקבל שגיאה במימוש הזה של קוד TypeScript. אני ממפה כאן סוג אחד לאחר. אבל VSCode מראה שגיאה שהמשתנה 'test' משומש לפני שהוא מוקצה. מישהו יכול בבקשה לעזור?

interface A {
   name: string;
   age: string;
   sex: string;
}

interface B {
   name: any;
   age: string;
   sex: string;
 }

const modifyData = (g : B) :A => {

    let test: A;
    test.name = g.name['ru'];
    test.age = g.age;
    test.sex = g.sex;

   return test as A;
};

const g = [{
  "name": {
      "en": "George",
      "ru": "Gregor"
       },
  "age": "21",
  "sex": "Male"
},
{
  "name": {
      "en": "David",
      "ru": "Diva"
       },,
  "age": "31",
  "sex": "Male"
}];

const data = g.map(modifyData);
console.log(data);

תשובה #1

כדי להבהיר קצת, זה תלוי בהבדל בין "מוקצה" ל"מוגדר". לדוגמה:

let myDate: Date; // I've defined my variable as of `Date` type, but it still has no value.

if (!someVariable) {
   myDate = new Date();
}

console.log(`My date is ${myDate}`) // TS will throw an error, because, if the `if` statement doesn't run, `myDate` is defined, but not assigned (i.e., still has no actual value).
   

הגדרה פשוטה פירושה לתת לה ערך התחלתי:

let myDate: Date | undefined = undefined; // myDate is now equal to `undefined`, so whatever happens later, TS won't worry that it won't exist.

תשובה #2

השגיאה מתרחשת משום ש-TypScript עדיין רואה את המשתנה כבלתי מוגדר בכמה תרחישים. הוספת ! לפני המשתנה אומרת ל-TypeScript להסיר את undefined או null כסוגים אפשריים עבור המשתנה:

let test!: A;

תיעוד של הצהרות הקצאה מוחלטת

מזחלת: typescript/מזחלת

תשובה #3

זה אכן לא מוקצה. הוא מוגדר, אך אין לו ערך.

לְתֵת דְּמוּיָה

let text: string; // variable `text` gets defined, but it has no assigned value - it is defined but unassigned
if (Math.random() > 0.5) {
  text = "heads";
}
// console.log(`We flipped ${text}`) // this would be an error for the compiler as the variable text might still not have a value assigned to it
text = "tomato"; // here we finally guarantee that text will have a value assigned to it and we can safely use it as string
console.log(`We found ${text}`)


לדעתי הצנועה, הדרך הנקייה ביותר תהיה להחזיר מילולי:

const modifyData = (g: B):A => {
    return {
        name: g.name['ru'],
        age: g.age,
        sex: g.sex
    } as A;
};