Search code examples
javascripttypescripttype-safety

how to maintain typesafe even after compile from ts to js


TS code :

function f(val1:number) {
    console.log(val1);
}

JS code, after compile :

function f(val1) {
    console.log(val1);
}

Is there any way to maintain type safe even after converting to js from ts?


Solution

  • There is no way to keep types after compilation to JS. JS has no concept of static types. Typescript is a static type checker, the output is plain JS. Therefore no types can persist after compilation.

    If you write your application in TS, the compiler will validate that what you are doing is type safe so at runtime things should work. (Although even in TS code you can break type safety and do unsafe things with any and type assertions)