Created
December 3, 2019 14:56
-
-
Save fvilante/7e5b468b77e21fdc811969b2020ef131 to your computer and use it in GitHub Desktop.
Can Typescript perform run-time check at compile-time ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Here we will put the solution. | |
// But before let's have a talk bellow. |
TYPESCRIPT SOLUTION
ERROR MESSAGE
Here is the error that bellow code produces at static-time in Typescript Playgound:
Argument of type '(_: string) => number' is not assignable to ...
Type 'number' is not assignable to type 'string'.(2345)
SOLUTION CODE
The code bellow is: informative, shorter at development and at run-time, and just has what is necessary to solve the proposed problem:
const f = (_:string) => 2 // note: sorry the strange syntax, it is just a function (nothing more than that).
const g = (_:number) => 3
const a = [1,1,1]
// const s = ['z','z','z'] , etc...
const r0 = a.map(g) // ok!
const r1 = a.map(f) // BAD ERROR!! But we know that at exactly moment we typed it. we cannot proceed until you solve that.
JAVSCRIPT TRANSPILATED CODE
Look that the Typescript output code is exactly equals the initial problem. No "run-time error detection code" will be generated or necessary.
"use strict";
const f = (_) => 2; // note: sorry the strange syntax, it is just a function (nothing more than that).
const g = (_) => 3;
const a = [1, 1, 1];
// const s = ['z','z','z'] , etc...
const r0 = a.map(g); // ok!
const r1 = a.map(f); // BAD ERROR!! But we know that at exactly moment we typed it. we cannot proceed until you solve that.
STUDY CASE 01 - CONCLUSION
Original answer:
Does Typescript type check in runtime ?
Response:
yes, in the sense that it avoids runtime checks bring the effect that they generate to static-time.
WHAT MORE ?
Can this technique be generalized ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JAVASCRIPT SOLUTION
I do not know other way in JS to DETECT this kind of error. Here is my solution:
SOLUTION CONSIDERATIONS
Ok, now at cost of some additional lines we have a "run-time error detection" mechanism that can stop our program execution if it's making a previsible mistake.