gpt4 book ai didi

typescript - 变量 'test' 在分配之前使用 - Typescript

转载 作者:行者123 更新时间:2023-12-02 23:58:26 25 4
gpt4 key购买 nike

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

最佳答案

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

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.

关于typescript - 变量 'test' 在分配之前使用 - Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44832316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com