typescripttypescript-typingstypescript2.0

Variable 'test' is used before being assigned - Typescript


I am getting error in this implementation of typescript code. I am mapping here one type to another. But vscode shows error that variable 'test' is used before being assigned. can anyone please help?

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);

Solution

  • It is indeed unassigned. It is defined, but it has no value.

    To give an example

    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}`)
    
    
    

    In my humble opinion, the cleanest way would be to return a literal:

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