Typescript Implicit vs Explicit types
Ahmedammarr
Posted on March 1, 2021
The expression implicit used to refer to something done behind the scene, on the other hand, explicit refers to the manual approach of applying things. from here let's discuss implicit and explicit typing in Typescript.
Type is the value that is annotated to a variable and it's compiled in run time, this helps catches errors in an early stage.
Implicit type means that the type is automatically declared for a variable.
So instead of annotating types explicitly
let isTrue: boolean = true;
we can let the compiler do it for us
let isTrue= true;
isTrue= 10;
//$ error: Type '10' is not assignable to type 'boolean'
Arrays and objects also can be implicitly typed
let typescriptArr = [1,2]
typescriptArr = ['X','Y']
//$ error: Type 'string' is not assignable to type 'number'.
let typescriptObj = {
userName : 'Ahmed',
age:25
}
typescriptObj.age = 'something'
//$ error: Type 'something' is not assignable to type 'number'.
notes: It's important to use descriptive names when using implicit type.
One more thing about implicit typing, variables declared without value are automatically assigned to type any and we can reassign it to any type.
let anyVar;
anyVar = 'Some String'
anyVar = 10
this will not through any errors, but take into consideration that it's not a good practice and the Typescript community does not encourage the use of any Implicitly or Explicitly
Finally, let's talk about the pros of implicit typing
1- Flexibility: this is one of the Typescript compiler strengths, unlike other strongly typed programming languages, we don't need to define the type for everything in our code.
2- Less Time Consuming: imagine refactoring a codebase with too much explicit typing, It'll take much time and efforts regarding the change of the time
Posted on March 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024