变量'测试'在被分配之前使用 - Typescript

时间:2017-06-29 18:16:13

标签: typescript typescript-typings typescript2.0

我在打字稿代码的实现中遇到错误。我在这里映射一种类型到另一种。但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);

2 个答案:

答案 0 :(得分:3)

为了澄清一点,这取决于“ assigned”和“ defined”之间的区别。例如:

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.

答案 1 :(得分:1)

确实是未分配的。它是定义的,但它没有价值。

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

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