typescript - typescript 对同一范围内的同一变量具有不同的类型
问题描述
value
这里有两种不同的类型。一个是string
,另一个是string | string[]
function getValue(value: string | (()=>string)):void{}
function test(value: string | string[]): void{
if(value instanceof Array){
return
}
// commenting out this line resolve the issue, but I don't know why?
// TS consider `value` here as string | string[], but it should be string only
value = 'string'
// `value` here is string
getValue(value)
// but here is string | string[]
getValue(()=>value)
}
解决方案
从这个答案,value
在闭包中getValue(() => value)
打破了control-flow-based-type-analysis。
有两种解决方案:
_value
用value声明一个局部变量string
。
function getValue(value: string | (() => string)): void { }
function test(value: string | string[]): void {
let _value = 'string'
if (typeof value === 'string') {
getValue(value)
getValue(() => _value)
} else {
// value is string[] type here
console.log(value)
}
}
- 使用类型断言
function getValue(value: string | (() => string)): void { }
function test(value: string | string[]): void {
value = 'string'
if (typeof value === 'string') {
getValue(value)
getValue(() => value as string)
} else {
// value is string[] type here
console.log(value)
}
}
推荐阅读
- logging - 将数据从(WAGO)PLC 发送到云数据库的最佳方式是什么?
- apache-superset - 如何将 Superset 与 gcloud oAuth 集成?
- python - 尝试将外部分数文件添加到 Python 猜谜游戏
- java - Java swing JScrollPane 不可滚动
- reactjs - Graphql Apollo useQuery 总是返回 new { data },即使它是从缓存中获取的。这合法吗?
- javascript - Javascript:将值列表转换为对象集
- html - 数据列表选项的方向在 Chrome 浏览器中没有改变
- python - AttributeError 没有属性“删除”
- java - 单击按钮将数据从服务发送到活动的最佳方式是什么?
- node.js - 元在 Winston-mongodb 中为空