Prevent JavaScript Typescript call without errors

Suppose I am writing a library with Typescript. There is a function with the following signature -

function check(value: "YES"|"NO"): boolean

So, when this function is called from other typescript files with values ​​other than "YES" or "NO", there will be a compilation error. But if called from a Javascript file, there will be no error, because Javascript has no type information. I can check for invalid values ​​inside my function and throw errors. But then the type safety provided by typescript seems to me only an illusion.

What should I do in this case as a library developer? Go with pure javascript? What did teams like Angular do?

+4
source share
1 answer

This is the difference between build time (compilation time) and error checking at runtime. TypeScript helps you with checking build time. Providing a TypeScript definition file with your library will help users get meaningful compile-time errors when they misuse your lib.

If your lib is consumed by JavaScript directly, you will not have a built-in step to notify the user, and you will have to resort to runtime messages. If file size is not a problem, I would suggest throwing a meaningful error message:

function (check) {
  if (check != "YES" && check != "NO") 
    throw new Error("Invalid Check Value: " + check);
  ...
}

If you are worried about file size, it might be best to just not work with invalid calls. Or have some reasonable default. It will depend on your situation.

"" , , .

+2

Source: https://habr.com/ru/post/1648365/


All Articles