functionf<Textendsstring|number>(a:T,b:T){if(typeofa==="string"){returna+':'+b;// no error but b can be number!}else{returnaasnumber+(basnumber);// error as b can be number | string}}f(2,3);// correct usagef(1,'a');// should be errorf('a',2);// should be errorf('a','b')// correct usage
I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
I am Software Developer, currently interested in static type languages (TypeScript, Elm, ReScript) mostly in the frontend land, but working actively in Python also. I am available for mentoring.
Yes, implementation of the value level can stay, but assertion like as X is a type level. Currently implementation cannot compile because of lack of proper typing, there is a way to solve it without any assertion that is why I left it as it is, so with compile error.
You can modify the implementation, the key is to have it working as original + typed safe.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
A quick idea -
Playground link
Nice, thanks but your code still doesn't compile, can you make a version which compiles? - Playground
Updated the answer :)
Now the interface of the function works in reverse way, what is correct is incorrect 😉
If i understood it correct, we are not allowed to change implementation of the method, just introduce types to make it work, right ?
Yes, implementation of the value level can stay, but assertion like
as X
is a type level. Currently implementation cannot compile because of lack of proper typing, there is a way to solve it without any assertion that is why I left it as it is, so with compile error.You can modify the implementation, the key is to have it working as original + typed safe.