How can I use IF and Const statements together in TypeScript?

Asked 2 years ago, Updated 2 years ago, 121 views

if (process.platform == 'win32'){
    constos: string = "I'm win32."
} } else if (process.platform == 'linux'){
    constos: string = "I'm Linux."
} } else {
  Constos: string = "Unknowns Target."
}

console.log(os)

I want to do this, but const is only valid within the if statement block, so I can't use it outside.

How can we solve this?

typescript const if문

2022-09-20 21:31

2 Answers

In such cases, I usually write it as below. Use mutable variables only within IIFE and assign them imutably when exporting out.

const os = (() => {
  switch (process.platform) {
    case 'win32': return "I'm win32"
    case 'linux': return "I'm linux"
    default: return "Unknowns Target."
  }
})()


2022-09-20 21:31

Is there a reason why it shouldn't be implemented like this?

lettmp="Unknowns Target."
if (process.platform == 'win32'){
    tmp = "I'm win32."
} } else if (process.platform == 'linux'){
    tmp = "I'm linux."
}
const os: string = tmp
console.log(os)

I don't know much about TypeScript, so I wonder if const has to be used like that.

Please let me know if it's a problem.

Thank you.


2022-09-20 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.