FewV minutes of Types in Typescript.
» Types in TypeScript
-
When creating a variable, there are two main ways TypeScript assigns a type:
-
Explicit and Implicit.
» Explicit
- Explicit - It means defining the type of a variable, Wether it is a string, number, or boolean.
let firstName: string = "John";
let myAge: number = 30;
» Implicit
- Implicit - It maens TypeScript will have to guess the type based on the assigned value.
let lastName = "Doe";
let age = 30;
-
This is called as infer, where TS have to guess the type of value
-
Implicit type assignment are shorter and are faster to type.
-
Now where we can get the error.
ERROR: TypeScript will throw an error if data types do not match.
Example
- Error for Explicit type:
let firstName: string = "John"; // type string
firstName = 33; // re-assigning the value to a different type
// Type 'number' is not assignable to type 'string'.
Here we defined the type of firstName to be a string and then if we try to re-assign it’s type, TypeScript will throw an error.
- Error for Implicit type:
let lastName = "Doe"; // inferred to type string
lastName = 33; // re-assigning the value to a different type
// Type 'number' is not assignable to type 'string'.
Here TypeScript already guessed the type of lastName to be a string and then if we try to re-assign it’s type, TypeScript will throw an error.
» Special Types
- There are special type which are used in TypeScript and they are Any, Unknown, never, null, undefined
» Any Type
-
Any type disable the type checking.
-
It is mostly not used in practice.
let hobbies: any[] = ["Cooking", "Sports", 5, true];
Console:
["Cooking", "Sports", 5, true]
» Unknown Type
-
Unknown is safer alternative to any.
-
Unknown is best used when we don’t know the type of data being typed.
let myHobbies: unknown[] = ["Cooking", "Sports", 5, true];
Console:
["Cooking", "Sports", 5, true]
» Never, Undefined, Null Types
-
Never, Undefined, Null are not used in practice.
-
They don’t hold much meaning in TypeScript.
// Never
let a: never = true; //never returns a value
// Undefined
let b: undefined = undefined;
// Null
let c: null = null;