变量 'test' 在赋值之前被使用 - 打字稿

Variable 'test' is used before being assigned - 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);

确实未分配。已定义,但没有值。

以我的拙见,最干净的方法是 return 文字:

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

稍微澄清一下,这取决于“分配”和“定义”之间的区别。例如:

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.

let test!: A;

添加一个'!'在变量名之后

参见:typescript/playground