简体   繁体   中英

Typescript specify/update variable type in switch

I want to define const type in block in switch case

Example


...

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
}

...

the only solution I found is to set new constant in switch blocks


...

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
}

...

is there some better way to set type just for typescript something like


...

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
}

...

real types of content are complicated interfaces but I simplified it for better understanding in general this works automatically but not in this scenarion I have

So my only question if it is possible to update/redefine/specify const type in some block

const cannot be reassigned. As mdn docs says :

The value of a constant can't be changed through reassignment (ie by using the assignment operator), and it can't be redeclared (ie through a variable declaration).

You can use let instead of const

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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