Hello fellow Developers, recently I am learning Typescript and I want to share my knowledge and journey along the way.
Basic Typescript Types
- Boolean
- Number
- String
- Array
- Enum
- Void
- Null
- Undefined
- Never
- Any
Type Annotations
Type annotation is a way to describe a variable type while declaration.
let name: string = "Anna";
name = 12; //returns error
Even if you don't annotate your variable, typescript infers your variable type on the base of the initial value.
let city = "Islamabad"; //city is type string here
city = 12; //returns error
And prevents you the assigning any value that doesn't match with the initial value type.
Union Types
Typescript allows you to assign more than 1 type to a variable which will result in a union
type.
const someVariable: string | number;
someVariable = "This is string"; //works perfectly
someVariable = 10; //works perfectly
Here someVariable
can have a string value or a number value.
Type Assertions
Type assertions are used when you are getting dynamic value in your variable and then you need to perform some operation on it.
let fixedString: string = (<number>num).toFixed(4);
Here with <number>
you are asserting the type of num
variable as a number. In other words, you are telling your code num
variable should have a number type.
There is another way to do it.
let fixedString: string = (value as number).toFixed(4);
Conclusion
In this blog, you learned about Typescript built-in types. How to Annotate and Assert variables in Typescript and last but not least How to create Union Types in Typescript.
Feel free to connect on Twitter
Top comments (0)