繁体   English   中英

Typescript 在开关中指定/更新变量类型

[英]Typescript specify/update variable type in switch

我想在 switch case 的块中定义 const 类型

例子


...

const content: undefined | number | string = apiData.content
let result
switch (apiData.type) {
    case: 1
       // update content type to only number
       result = content * 5
    break

    case: 2
       // update content type to only string
       result = content + ' is string'
    break
}

...

我找到的唯一解决方案是在开关块中设置新常量


...

const content: undefined | number | string = apiData.content
let result
switch (apiData.type) {
    case: 1
       const newContent = content as number
       result = newContent * 5
    break

    case: 2
       const newContent = content as string
       result = newContent + ' is string'
    break
}

...

有没有更好的方法来设置 typescript 之类的类型


...

const content: undefined | number | string = apiData.content
let result
switch (apiData.type) {
    case: 1
       typeof content is number // set type
       result = content * 5
    break

    case: 2
       typeof content is string // set type
       result = content + ' is string'
    break
}

...

真正的内容类型是复杂的界面,但我简化了它以便更好地理解一般这会自动工作,但在这种情况下我没有

所以我唯一的问题是是否可以在某个块中更新/重新定义/指定 const 类型

const不能重新分配。 正如 mdn 文档所说

常量的值不能通过重新赋值(即使用赋值运算符)来改变,也不能重新声明(即通过变量声明)。

您可以使用let代替const

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM