#Is it worth to switch from js to ts

16 messages · Page 1 of 1 (latest)

versed turret
#

type safety is about misusing values

#

code analysis can do things like checking for incorrectly-used promises, or a switch that's not coherent, or a function that will never return

#

things that aren't about the types themselves

fast trout
#

could u show me an example?

#

it would make understanding easier

versed turret
#
function forever(n: string): void {
  while (typeof n === 'string') {
    console.log(n.toFixed(2));
    if (typeof n.toString() !== 'string') {
      break;
    }
    // ...
  }
  console.log("Done");
}
```static typing allows `n` to be documented as a `string`
static analysis can then go through this code with that knowledge, and see that
- `n.toFixed()` is incorrect, because `string` doesn't have a `toFixed()` method. this is type safety.
- `typeof n === 'string'` is always true because `n` is defined as a `string`
     so that must mean the `while` always continues
     the `while` has a conditional `break` - the condition is `typeof n.toString() !== 'string'`
        `n` is a `string`, which defines `n.toString()` to be a `string`
        so this condition is always false
            so this `if` never runs
                so this `break` never runs
        the `while` never exits.
        `console.log("Done");` is after the `while`, and is unreachable.
this is what code analysis can do. and this all relies on `n: string`.
fast trout
versed turret
#

no, it wouldn't break

#

it would just not be able to catch that

#

but plain js catches zero of this

fast trout
#

yeah ik

fast trout
#

anything other, or is it just those 2 things?

versed turret
#

type info lets you get pretty good autocomplete and hover stuff

fast trout
dusk halo
#

I switched to ts and had the same question and i personally think its worth it