DEV Community 👩‍💻👨‍💻

Discussion on: How the TypeScript Required Type Works

Collapse
 
smpnjn profile image
Johnny Simpson Author

I'll try to explain what TypeScript is briefly. All data has a type when we program something. For example, 5 is a number, "this-is-a-text" is a string, etc.

Javascript figures out the types by itself - so you never mention them in your code. That means if you write:

let x = 5;
Enter fullscreen mode Exit fullscreen mode

Javascript figures out it is a number. However, if we wrote:

let x = "5"
Enter fullscreen mode Exit fullscreen mode

Javascript will think it's a string, since we put 5 in quotation marks. This can mean in complicated applications, bugs can start to arise because we don't "enforce" types. For example "5" + "5" is 55, but 5 + 5 is 10.

Ideally, we would "enforce" "5" to be a number. TypeScript tries to fix this problem by adding types into Javascript, so they are all defined up front. Instead of the above, we write:

let x:number = 5;
Enter fullscreen mode Exit fullscreen mode

Now if "x" is not a number, we'll get an error. That way we can avoid bugs in our code.

Collapse
 
fathidevs profile image
fathidevs

thank you so much