如何解析Typescript中的局部范围变量?

问题描述

我正在尝试在我的 React 应用程序中将字符串解析为对象数组。

const {newsEntity} = props;
const contentInString = {newsEntity.content}; <== not working
// const contents = JSON.parse(contentInString); <== hoping to use this someday

我收到以下错误 ESLint: Parsing error: ',' expected.

我试图删除花括号,但它给出了 undefined

内容

[{"content":"Umi Kalsum berharap kondisinya tetap baik","type":"text"},{"content":"Dream - Setelah menempuh perjalanan darat cukup panjang untuk menemui wanita diduga telah menghina keluarganya,Umi Kalsum dan Ayah Rozak akhirnya kembali rumahnya di Depok,Jawa Barat. Perjalanan panjang itu ternyata menguras tenaga orang tua Ayu Ting Ting tersebut.","type":"text"}

我注意到 {newsEntity}内容仅在渲染期间可见

return (<div> {newsEntity.content}</div>  );

解决方法

const contentInString = {newsEntity.content}; 这会导致语法错误。

你应该这样提取const contentInString = newsEntity?.content

,

如果你想分配新的对象使用:

const contentInString = {content: newsEntity.content};

如果您想从 content 获取 newsEntity,请使用:

const contentInString = newsEntity.content;

关于问题的最后一部分 - 这是 TypeScript 错误,它提示您您的类型出现问题。 你可以或

  • 创建新变量并自动推断类型
  • 或手动修复类型
,
//Checkout this hopefully this will help you
let GblVar=100;  
 
function Fn() {          //function
 
  console.log(GblVar)
 
  if (true) {         //code block
    console.log(GblVar)
  }
 
  function nested() {         //nested function within someFn1
    console.log(GblVar)
  }
 
}
 
for (let c = 0; c < 3; c++){    //code block
  console.log(GblVar);
}
 
function OthrFn1() {       //another function
  console.log(GblVar)
}
 
console.log(GblVar)