我在打字稿代码的实现中遇到错误。我在这里将一种类型映射到另一种类型。但 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.
确实是未分配。它被定义了,但没有任何价值。
举个例子
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;
};