Typescript in HTML

The point of Typescript, as with every single other statically typed language , it that it typechecks the code before compilation. And like essentially every other statically typed language, that type information is stripped from the compiled output. Programming languages aren’t user input validators. You can write a validator in a programming language, but the language itself is not the validator.

Because you actually have to write the code. If you didn’t have to write the code, then sure it’s not an issue, but you do, and IRL TS a. tends to provide much more confidence in program logic as it makes certain program states impossible, and b. tends to make codebases easier to understand (it is easier to write tools to inspect them). All YMMV, naturally.

Because it’s not a runtime validator: it checks the code, not the runtime use of the code. JavaScript already does runtime typechecking, and you can do more if you need to via conditional guards, as you described. It isn’t TS’ job to generate that; it is the programmers – TS cannot really anticipate how an arbitrary end-user will use {some code}.

1 Like

Thank you for your elucidating comments, Dan. But doubts still linger.

Suppose you write:

interface Person {
name: string,
}

class Employee implements Person {
public name: string;
public id: number;

constructor(name: string, id: number){
this.name = name;
this.id = id;
}
}

let employee = new Employee(“Susan”, 44);

In JS:

class Employee {
constructor(name, id) {
this.name = name;
this.id = id;
}
}
let employee = new Employee(“Susan”, 44);

Adding basic input validation:

“use strict”;
class Employee {
constructor(name, id) {
if(typeof name == “string” && typeof id == “number”) {
this.name = name;
this.id = id;
} else {
throw new Error(“Invalid input”)
}
}
}

try {
let employee = new Employee(“Mary”, 99)
} catch (e) {
console.log(e.message)
}

I understand that TS checks the code and not its runtime use. The above example illustrates no such use but a JS implementation of the type checking carried out by TS. If we could use TS directly in the browser, JS validation (and JS itself) wouldn’t be needed and TS would be a winner. Why work with TS in this case when I can achieve more with JS with less time? What scenarios make evident the advantages of TS over JS?

You have given me an explanation of an elementary TS topic that doesn’t address at all the issue my question raises.

function fullName( firstname: string, blastname: string ):string {
return firstname.concat(" ").concat(lastname);
}

If you call the function fullName with mismatching types in a TS environment, the ide or the compilation will complain. If you call the function in your code with mismatching types JS won’t complain and your programm will output ‘Mar6 Smith’ unless you write regular expressions for input validation.

If you write a complex TS class as part of a big code base and inadvertently try to instantiate it in a TS environment using a constructor argument with a mismatching type, the ide or the compiler will pinpoint the error while the JS environment won’t and you may not realize your mistake until compile-time. That means you have to implement the same basic type checking in JS that TS does( not advanced one ), which brings up the question on why use TS to begin with when I can achieve the same result in less time using JS.

You have established that TS isn’t an input validator for users? Did I say that it was? Obviously it does input validation in its own environment. Is that not so obvious that it needs establishing?

Again, that isn’t achieved by JS unless the developer takes the extra step, which exemplifies the issue my question raises. If I were looking for a JS library, I would obviously not have posted the question to inquire about possible drawbacks of TS. I’m not here to dispute its efficiency but to receive enlightening explanations as to the extent of its value, which I don’t feel I’ve received as of yet. Making innuendos about someone’s programming background doesn’t clarify the matter either.

Because it’s for writing programs. It ensures (to an extent), that the program you write is logically correct before the program is compiled to the code that actually runs in the browser. It can’t anticipate user input, that’s not the reason the language exists.

The is the same for every single language: if input comes into the program from the external world (which is the only place, in your example, where it could come from), what’s a boolean? What’s a number? What’s a string? These things are completely arbitrary concepts and only make any logical sense in the context of writing a program in a given language. Outside of that they’re just bytes in some order

You normally only require validation at the external points of the program, the places where it interacts with the outside world. Once you determine what {some data} is, then off it goes into the program. Sure, the program compiler could auto generate very basic type checks of the kind you describe, but then it’ll do that for every single bit of logic. So every single time your program does anything, it will run these checks, which

a. are slow,
b. are mostly going to be pointless,
c. aren’t meaningful (2e3673 is a number, so is -0.0000000000623, so is 0b11010, are they valid IDs?)
d. happen at runtime (in contrast to static compile time analysis, which does not)

No language designer is going to do what you suggest, because it makes no sense when you actually think about it.

In your example, in what context is that constructor being ran where the input may be unexpected? It may well be one where you do need a typecheck. That’s fine, but you need to figure out if it’s necessary or not (and while.ypu are developing, in this case, the Typescript compiler will do its best and tell you whether it’s required or not)

However, what the input needs to be to that constructor is very important during development of the program, because having a tool that will tell me immediately whether some logic that depends on that class will work or not, that’s really important information that I need to know right away when I’m developing, not just at runtime.

Who in his right mind would imply or say explicitly that TS code has any business dictating how an HTML page functions since HTML only recognizes JS? Are you not having a problem doing basic text analysis? Instead of trying to undermine my arguments for no logical and honest reason, why do you not make an effort to answer the question the post proposes in a clear and convincing manner instead of saying TS is what it is? Instead of making a facetious suggestion to turn my question into an issue that the TS team should deal with? Am I here to disparage the role of TS? Why haven’t you bothered to read my other comments if you’re having a hard time understanding what it is I’m looking for enlightenment on?

You can’t.

How often are you interacting with web pages you didn’t code yourself by calling JavaScript functions from the browser console? That sort of use case is the only time I can think that you would run into this sort of issue. Generally people interact with web pages via input elements and buttons, etc.

1 Like

“You were already given numerous correct answers that for whatever reason you refuse to accept or just do not have enough programming experience to understand.”

If those answers were correct, how come you were unable to prove that with either irrefutable arguments or examples? Does anything speak louder than code?!

“No, but you seem to have trouble reading and understanding very cohesive responses from several members here.”

Again, you keep using labels but you don’t prove your point by illustrating it.

“HTML only recognizes JS??? What are you trying to say here.”

I said that HTML recognizes only JS, implying that it doesn’t recognize TS! Since this discussion revolves around those two languages, do I need to dot the i’s and cross the t’s every step of the way to make myself clear? Do I sound so naive that I give the impression of being ignorant of HTML being able to incorporate technologies such as CSS, JQuery, Bootstrap, etc.? I wrote numerous times that HTMl doesn’t recognize TS and that’s what I based my post on. Now go ahead and say that I’m not making myself clear enough…

“No one is trying to undermine your arguments, but based on your responses, you seem to have already made up your mind about what TS should be doing regardless of the fact that we have pointed out the contrary.”

Do I need to comment this one or should I repeat with others words the above-mentioned? Leave the labeling for those who evade the harder task of interpreting correctly and backing up their arguments with code and correct information.

All TypeScript does is make sure that the developer is writing code where the use of a variable matches the type of data stored in the variable. It makes sure the code is logically consistent.

TypeScript has no way of knowing what inputs will be passed to the code while it is running. Any inputs from outside of the TypeScript that was written need to be verified before they can be stored into an appropriate variable.

Now the moment of truth. I’ve been keeping silent about it to see how far this crazy debate would go.

If I use two text fields to get the first and last name of a user to return his full name, will the browser complain if he makes a typo and enters a digit instead of a character? No. Will JS complain if you don’t write input validation code? No. Would you as a developer be content if your app outputted “Louis Smit9” without warning the user? Maybe you would…

You and all the others here seem to forget that Typescript is a superset of Javascript. Therefore, TS not only does type checking but has no problem handling input validation written in JS.

TS

function fullname(firstname: string, lastname: string) {
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
} catch (e: unknown) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
} else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

JS

function fullname(firstname, lastname) {
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
}
catch (e) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
}
else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

ps. Freecodecamp didn’t allow meto include the regex expression.

Here is another chance for you to show your cohesive arguments:

1.In this particular scenario, do you see any advantage of using TS instead of JS?
a. If you answer yes, pinpoint where and explain.

b. If you answer no, what does that suggest? Is TS relevant in this particular case or in all cases to guarantee code robustness? How does all this answers the question of the post? Do not only think in terms of input through the browser. As a developer, nothing stops you from using CLI to test your code.

  1. Can you write simple code that clearly shows the benefits of TS? Since the language has taken the developer community by storm, surely those cases exist. If you can’t, that’s fine. That only hints at the fact that TS unleashes its powers in more complex projects involving node.js, react.js, etc.

  2. Did anyone anywhere conveyed the same ideas with different words? If so, pinpoint that and explain.

You seem really hung up on this user data validation, but that isn’t what TypeScript is for. TypeScript only checks that you write consistent code. It knows nothing about the user.

“TypeScript only checks that you write consistent code. It knows nothing about the user.”

  1. OK. Then you also agree that TS isn’t needed for writing that consistent code you mentioned in cases like the one below, correct?

TS

function( firstname: string, lastname: string) {
return firstname.concat(" ").concat(lastname);
}

JS

function( firstname, lastname) {
return firstname.concat(" ").concat(lastname);
}

  1. Do you agree that all apps that require typed input from users need to implement user validation? If you’re writing a large code base using TS and part of the code includes input validation, is there anything that stops you from writing it in TS?

If I use two text fields to get the first and last name of a user to return his full name, will the browser complain if he makes a typo and enters a digit instead of a character? No. Will JS complain if you don’t write input validation code? No. Would you as a developer be content if your app outputted “Louis Smit9” without warning the user? Maybe you would…

Should developers not be “hung up” in input vaidation then? This debates also revolves around the merits of TS over JS as far as that is concerned.

The thing you are essentially asking, even if you don’t realise this, is “why use a statically typed language when there are dynamic languages”. There are arguments pro and anti and acres of discussion going back almost half a century on this subject.

ie “why use Java when Ruby exists”, “why use C++ when Python exists”.

That’s fine, but it has nothing to with validating input, which is what it very much appears you’re confusing this with.

A programming language is not an input validator. You may write an input validator in a programming language, but the language itself is not the validator. That isn’t the purpose of a programming language

2 Likes

Nope. I like strongly typed languages. They prevent bugs.

Yup

Nope

1 Like

"The thing you are essentially asking, even if you don’t realise this, is “why use a statically typed language when there are dynamic languages”.

Incorrect. TS hasn’t taken the developer community by storm, which suggests that the language surely unleashes its power in scenarios more advanced than the one I proposed.

“A programming language is not an input validator.”

  1. Did I say or imply anywhere that it was? Do you agree that all apps that require user input ( which are found by the millions ) require user input? It’s a fact and not about me being hung up on user input. If I use two text fields to get the first and last name of a user to return his full name:

Will the browser complain if he makes a typo and enters a digit instead of a character? No.

Will JS complain if you don’t write input validation code? No.

Would you as a developer be content if your app outputted “Louis Smit9” without warning the user? Maybe you would…

  1. You seem to forget that TS is a superset of JS. If you’re writing a large code base in TS, is there anything that stops you from writing your input validation in TS?

  2. That being said, if your program is comprised solely by the code below, is there any point in using TS when you could easily achieve the same result using JS…?

TS

function fullname(firstname: string, lastname: string) {
const regex = /[1]{1, 15}$/;
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
} catch (e: unknown) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
} else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

JS

function fullname(firstname, lastname) {
const regex = /[2]{1, 15}$/;
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
}
catch (e) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
}
else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

This debate is not about downgrading the merits of TS. It’s a language that has taken the developer community by storm, so surely there are cases when it clearly unleashes its power.

  1. Can you provide me with a simple code that clearly demonstrates such sefulness if the above-mentioned doesn’t say anything to you?

This time I have numbered my questions to make sure you don’t miss any of them.


  1. a-zA-Z ↩︎

  2. a-zA-Z ↩︎

The whole point of TS is to help the developer write less bad code. It has in fact taken web dev by storm - that’s why frameworks use TS.

Absolutely nobody has said or implied this.

Nobody has forgotten this. If you are working on a project written in TS, everything is written in TS, to include input validation. That TS gets transpiled to JS for the browser to understand, and that compilation process checks for errors in type agreement with the variables and functions the developer wrote.

The point would be that TS helps you ensure that the developer wrote code that uses types consistently. Developers write bugs. TS catches the type based bugs for you.

The question of user input has absolutely nothing to do with TS. You need to validate user input. Your app might be written in TS or JS. If your app is written in TS, then all you your code gets checked for type based bugs. If you write it is JS, then your code is not checked automatically in that way. In either language, input validation is mandatory if you want to prevent bugs introduced by the user.

“Would you as a developer be content if your app outputted “Louis Smit9” without warning the user? Maybe you would… Absolutely nobody has said or implied this.”

Nobody would make a fool of himself by explicitly stating that. But if you had taken the time to go through all the comments above, you’d have realized that no one acknowledged the role TS has in doing input validation.

“If you are working on a project written in TS, everything is written in TS, to include input validation. That TS gets transpiled to JS for the browser to understand, and that compilation process checks for errors in type agreement with the variables and functions the developer wrote.”

Is that news to anyone on this page?

  1. Would you say that there is any relevance in writing the TS code to catch bugs as the example below shows? If there is, show me where and explain why.

TS

function fullname(firstname: string, lastname: string) {
const regex = /{1, 15}$/;
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
} catch (e: unknown) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
} else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

JS

function fullname(firstname, lastname) {
const regex = /{1, 15}$/;
if (regex.test(firstname) == false || regex.test(lastname) == false) {
try {
throw new Error(“Incorrect input.”);
}
catch (e) {
if (e instanceof Error) {
alert(${firstname} ${lastname}. ${e.message});
}
}
}
else if (regex.test(firstname) == true && regex.test(lastname) == true) {
alert(${firstname} ${lastname});
}
}

“The point would be that TS helps you ensure that the developer wrote code that uses types consistently. Developers write bugs. TS catches the type based bugs for you.”

  1. You keep stringing on the same harp. Can you then provide me with code that clearly shows how that type checking in TS influences the catching of bugs when it is its JS counterpart, stripped of all type checking, the one interacting with the browser or any other input medium?

Would you say the code below proves your point?

TS

interface Person {
name: string,
}

class Employee implements Person {
public name: string;
public id: number;

constructor(name: string, id: number){
this.name = name;
this.id = id;
}
}

In JS:

class Employee {
constructor(name, id) {
this.name = name;
this.id = id;
}
}

Show me the code…

“The question of user input has absolutely nothing to do with TS. You need to validate user input.”

  1. And how do we validate user input? Waving a magic wand? Of course you have to write the validation, either in TS or JS. How can you then say that it has nothing to do with TS when it is the very tool that allows us to write that code?

  2. Since you say that TS helps catching bugs, can you provide me with code that shows how that can be?

I am not here to disparage the role of TS. It wouldn’t have taken the developer community by storm if it hadn’t proven its power. My point is that no one here has as of yet shown me where that power lies.

I have numbered my questions to make sure you don’t miss any of them.

1 Like

Yes, and the reason I say that is that there are only two likely scenarios where that class in your example is going to be instantiated with an incorrect value:

  1. a malicious attempt to do something untoward, in which case the check isn’t really going to help because at that point the bad actor has to have direct access to the code, or
  2. user input, or more specifically unknown input (could be from an external API, for example)

If neither of those scenarios are in play, then the typecheck is simply there as a form of defensive programming, ie it’s being used to ensure the program works, logically. Which is what Typescript does, except TS does it before the code is compiled. This is a way of proving the logic works without running the code. So you develop using a statically typed language, which may provide a much more satisfactory level of confidence that the code will function as expected when it is actually ran.

It absolutely has, I would be extremely surprised IRL to be placed in a situation where a codebase does not use Typescript.

Obviously that is true, because types are stripped from the output code. That is not the point of using a statically typed language

On my Android phone, I can only type numbers in when I want to enter a phone number. Java is a statically typed language, yet it is not Java stopping me entering anything that isn’t a number due to the type system, it is stopping me entering them because there is some code a programmer has written (similar to your regex) that checks what the values entered into the input are.

A large % of the languages used IRL are statically typed and compiled. But when they are compiled, the output is just some bytecode or machine code instructions. All the statically typed stuff, all the semantics and syntax, that is just there as an abstraction for humans to be able to write instructions in a sane manner.

That’s what TS is. JavaScript is not statically typed, and not being statically typed has some benefits. As you say, TS is just a superset of JS and you can write everything in JS if you want. Yet TS is incredibly popular. Which should be a hint that people find the benefits of a statically typed layer on top of JS to be something that is extremely helpful.

It doesn’t magically cause your code to tell you if there is unexpected input at runtime. What you’re suggesting may seem simple and self-evident, but it isn’t at all. There are languages that can do this, that can include program state in the type system, they have been a research subject for at least 50 years. But afaik the only real existing usable implementations are either severely constrained (mathematical proof checkers like Coq, which are not turing-complete), or they involve dependent types, which are insanely complicated to work with (research languages like Idris or Agda).

Edit: is a given program correct? That is the question TS attempts to answer. And it can’t completely prove that, but it can go much further than JS can. This short talk is good:

https://www.destroyallsoftware.com/talks/ideology

1 Like

TS has zero role in input validation. That’s the role of the developer. We have said this repeatedly.

I read the conversation. I think you are not understanding what people are telling you.

Because this is the one and only purpose of TS - catching type mismatches in written code.

These are still utterly unrelated. Input checking has nothing to do with type checking the code the developer wrote.

Any language can do input validation. Language choice has nothing to do with the need for input validation.

The power is in type checking the code the developer writes. Its benefits have absolutely nothing to do with the need to validate user input. That is utterly unrelated to the purpose of strongly typed languages.

To make a simple toy, TS prevents bugs that look like

const result = iNeedAStringInput(5);
1 Like

When you’re working on a team, often times you need to be able to make changes to a part of a large code base, comprised of hundreds or thousands of files, and often times you were not the one who originally wrote that code, so you’re unfamiliar with it.

So let’s say you need to update the UI for the employee page, and there’s some function like this in JavaScript:

renderEmployeeDetails(employee) {
  // ...
}

In JavaScript, you have no idea what properties are on that employee object by just looking at this file. Do they have a name, or firstName, or first_name? The Employee class definition is not in this file so you can’t know. Even if there were an Employee class in some other file, you can’t yet be sure that the object this function is getting is an instance of that class. So you would need to do some debugging like logging the object to the console, running the dev server, then finding the log to confirm what properties are on the object. Or you might look for places calling this function and following the chain up until you find the place that instantiates the object. All in all, these sorts of things take time and can be frustratingly unclear depending on the project’s structure.

However in TypeScript, it’d likely look more like this:

import { Employee } from '@/types';

renderEmployeeDetails(employee: Employee) {
  // ...
}

In which case you right click on Employee in your IDE, select show definition which takes you to the interface, and then see bright as day what properties are on it. This makes you much more confident to make the necessary changes.

At least that’s why I much prefer to use TypeScript.

2 Likes

This conversation has become vitriolic and unproductive. I am closing this thread.