1

Use Case - I have a typescript based project, that transpiles to a standalone library via webpack.

  • to initiate the library, we have to pass arguments,which is an Object, lets call it initOptions.
  • this initOptions corresponds to a **InitOptions ** interface.
  • typeScript throws an error, if desired arguments are not passed according to the interface.
  • Same transpiled code to JS, does not throw any error as such.

Is it the standard behavior? For my use case, do i need to have explicit checks for arguments as well?

suppose the library has a init method that expects initOptions according to below interface -

// this is somewhat how library looks like
interface InitOptions = {
  arg1: String,
  arg2: String,
  arg3: String
}
function init(options: InitOptions): someOtherInterface {
 return "something"
}

<!------------------------------------------------------------------------------------->

// Running in the dev env in typeScript

let initOptions: InitOptions = {
  arg1: "sample",
  arg2: "sample"
}
lib.init(initOptions) // throws an error as the arguments does not matched the interface.

<!------------------------------------------------------------------------------------->

// when running after transpiling the code as a library, it throws no error in this scenario
let initOptions: InitOptions = {
  arg1: "sample",
  arg2: "sample"
}
lib.init(initOptions) //throws no error at all

So again, my question is, do we need to have explicit checks if we want to have a strict checks for arguments? Doesn't typeScript ships this functionality to JS when translpiled?

1 Answers1

1

Doesn't typeScript ships this functionality to JS when translpiled?

Absolutely not.

This Typecript:

// this is somewhat how library looks like
interface InitOptions {
  arg1: String,
  arg2: String,
  arg3: String
}
function init(options: InitOptions): string {
    return "something"
}

Is this JS:

"use strict";
function init(options) {
    return "something";
}

Everything related to types is gone after compilation.


The point of types are to aid in development. The only benefit to compiled production code is that you hopefully have less bugs due to incorrect use of your applications data.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337