DEV Community

Cover image for Typescript Implicit vs Explicit types
Ahmedammarr
Ahmedammarr

Posted on • Updated on

Typescript Implicit vs Explicit types

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;  
Enter fullscreen mode Exit fullscreen mode

we can let the compiler do it for us

let isTrue= true;  

isTrue= 10;

//$ error: Type '10' is not assignable to type 'boolean'
Enter fullscreen mode Exit fullscreen mode

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'.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)