Typescript specify/update variable type in switch

Viewed 16

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

1 Answers

const cannot be reassigned. As mdn docs says:

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

You can use let instead of const

Related