在分配之前使用变量“test" - Typescript [英] Variable 'test' is used before being assigned - Typescript

查看:37
本文介绍了在分配之前使用变量“test" - Typescript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行打字稿代码时遇到错误.我在这里将一种类型映射到另一种类型.但是 vscode 显示在分配之前使用了变量test"的错误.有人可以帮忙吗?

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

推荐答案

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

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

在我看来,最简洁的方法是返回一个字面量:

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

这篇关于在分配之前使用变量“test" - Typescript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆