变量“test”在分配之前使用 - Typescript

问题描述 投票:0回答:3

我在打字稿代码的实现中遇到错误。我在这里将一种类型映射到另一种类型。但 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);
typescript typescript-typings typescript2.0
3个回答
107
投票

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

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.


82
投票

触发错误是因为打字稿在某些情况下认为变量仍然为未定义。在变量之前添加

!
告诉打字稿删除未定义或 null 作为变量的可能类型:

let test!: A;

明确赋值断言文档

游乐场:打字稿/游乐场


19
投票

确实是未分配。它被定义了,但没有任何价值。

举个例子

let text: string; // variable `text` gets defined, but it has no assigned value - is 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
console.log(`We found ${text}`)


以我的愚见,最干净的方法是返回字面值:

const modifyData = (g: B):A => {
    return {
        name: g.name['ru'],
        age: g.age,
        sex: g.sex
    } as A;
};
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.