In this article, we will explore statical typing in typescript and what makes the language optionally statically typed.
TypeScript is a strongly typed programming language that builds on top of JavaScript. TypeScript allows specifying the types of data being passed around within the code and has the ability to report errors when the types don’t match.
What is Statically Typed Language ?
In a statically typed language, type checking occurs at compile time. The compiler enforces the value to use the same type. Let’s see an example, which is valid in javascript.
let value = 5 value = "Hello World"
Output:
Error: Type 'string' is not assignable to type 'number'.
The type of value changes from a number to a string. This is forbidden in TypeScript.
How Typescript Is Optionally Statically Typed ?
Typescript allows assigning type to a variable. Typescript can also infer the type based on the initialization of the variable. There may be an instance where we want to store a value in a variable but don’t know its type at the time of writing the program. In this case, we want the compiler to opt out of type checking and pass the value without any errors. Typescript has any type which allows us to store any type of value and skip type-checking.
Example 1:
Typescript
let value: any = 5; console.log(value); value = "hello" ; console.log(value); |
Output:
5 hello
Here, the value can be changed from a number type to a string type without any compilation error. It instructs the compiler to skip type-checking.
Example 2:
Typescript
function add(a: any, b: any): any { if ( typeof a === 'number' && typeof b === 'number' ) { return a + b; } if ( typeof a === 'string' && typeof b === 'string' ) { return a.concat(b); } } console.log(add(3,6)); console.log(add( "Hello" , "TypeScript" )); |
Output:
9 HelloTypeScript
In this example, the add() function will calculate the sum of the values passed if they are numbers. If they are string, the add() function will concatenate them into a single string.
This property of typescript contradicts the definition of statically typed programming language. Therefore, TypeScript is also called an optionally statically typed language.