[Typescript] Function scope in typescript
typescript in Function Scope
2023-09-14 08:59:11 时间
We have the following code which has compile error:
async function readData(event?: Event | unknown): Promise<void> {
// ...
let text: string | undefined
// ...
if (!text) return
setData((state) => ({ ...state, data: text })) // Typescript doesn't compile because text is still `string | undefined`
}
Main reason is about function scope, text
is defined in readData
function, and we try to use it in another function scope (
state
) => ({ ...
state
, data: text })
, because two different function scopes, therefore text
remains type string | undefined
Solutions to resolve this issue:
- Move to
readData
scope
if (!clipboardText) return
const data = clipboardText // move it here
setClipboardData((state) => ({ ...state, data }))
2. Move to arrow function scope
setData((state) => {
if (!text) return state;
return {
...state,
data: text
}
})
相关文章
- 快速掌握 TypeScript 新语法:infer extends
- 如何处理TypeScript中的可选项和Undefined
- TypeScript(node)连接使用MySQL(JavaScript也一样)
- Create Your Own Redux (Typescript)
- TypeScript 实用工具类型之 Pick 类型
- TypeScript超详细入门教程(上)
- TypeScript 类型体操:提取对象指定 key 并设置为必填
- TypeScript笔记
- (十四)与 TypeScript 集成
- Typescript 全栈最值得学习的技术栈 TRPC
- 【TypeScript】条件语句
- 开心档之TypeScript 变量声明
- 在TypeScript中使用装饰器
- ORA-28004: invalid argument for function specified in PASSWORD_VERIFY_FUNCTION string ORACLE 报错 故障修复 远程处理
- Oracle游标IN模式使用指南(oracle游标in)
- 关键字使用Oracle中的Replace函数替代IN关键字(oracle替代in)
- 方法掌握MySQL中IN方法的威力(mysql的in)
- TypeScript 2.0 与 AngularJS 2.0 的新动态
- 如何在MySQL中代替IN关键字(mysql中代替in)
- MySQL中使用IN函数的查询限制是什么(mysql中in的限制)
- MySQL中如何使用IN操作符(mysql中in怎么写)
- 深入剖析MySQL中IN和等于操作的差异与应用(mysql中in和等于)
- MYSQL中IN关键字如何高效处理大量数据(mysql中in关键字)
- Oracle的IN走索引技术(in走索引 oracle)
- MySQL如何使用IN查询语句(mysql不能用in吗)
- 条件在Oracle中使用IN和OR查询条件的巧妙之处(oracle中in跟or)
- 条件Oracle查询使用两个IN条件(oracle 两个in)
- Oracle 中的 IN 子句使用技巧(oracle in 子句)