【问题标题】:Variable 'test' is used before being assigned - Typescript在分配之前使用变量'test' - Typescript
【发布时间】:2017-12-03 13:53:39
【问题描述】:

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

【问题讨论】:

  • let test: A 定义了test,但没有将其分配给任何东西。因此,在设置其name 属性时会出现运行时错误。编译器试图告诉你先分配它。
  • 如果我想这样做,请测试:A = { name: '', age: '', sex: '', };那么它工作正常吗?
  • 试试看...好像你想要的是let test:A = { name: g.name['ru'], age: g.age, sex: g.sex };
  • 效果很好。谢谢迈克。我是 TS 的新手。 :)

标签: typescript typescript-typings typescript2.0


【解决方案1】:
let test!: A;

添加一个“!”在变量名之后

见:typescript/playground

【讨论】:

  • 答案可能有用,但至少对我来说不是。简要说明什么!在这里的意思,会很方便
  • 这里的主要思想是,Typescript 计算所有可能的场景,即使是那些乍一看并不那么明显的场景,因此它的推理能力遇到了可能的nullundefined 类型。因此,如果您确定某个变量实际上不会是nullundefined,您可以通过后缀! 来提示TS,它只是从表达式类型中删除nullundefinedMore info
  • 另一种说法是!运算符意味着您想告诉编译器您最了解。您断言将始终指定该值。您很少需要这样做,因为在运行时很容易被抓到。
【解决方案2】:

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

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.

【讨论】:

  • 是的,谢谢,这是我的问题。您不需要显式分配 undefined - TS 只需要知道它是预期的:let myDate: Date | undefined;
【解决方案3】:

确实没有赋值。它被定义了,但它没有任何价值。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2020-07-25
    • 2019-11-06
    • 2021-08-16
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    相关资源
    最近更新 更多