Learn TypeScript:Part 2 → Type declaration.
Learn basic features of typescript
Create a new file with extenstion .ts
,say add.ts
In that file we will create a variable a
, then assign different types of values then see what typescript says
When we compile the code using tsc add.ts
. It generates a.js file in the same folder . And it doesn’t reports any error.
So now let’s try to add a type to a then test if TypeScript allows us to assign different types of values to variable a
number
is the datatype . So when we assign a string to a variable which is declared as type Number it will throw error.
If you’re using VSCode IDE then this error will be warned when you’re writing (which means you don’t need to compile it ).
So as a first step let’s write the add
function in Typescript.
: number
in function() : number
is the return type of the function.
If we call the method like --------------------------------------------------------------------1.addNumber(1)
//error2 function addNumber(num1 : Number , num2 : Number): Number {~~~~~~~~~~~~~An argument for 'num2' was not provided.--------------------------------------------------------------------2. addNumber("hi","hi");// errorArgument of type '"hi"' is not assignable to parameter of type
'Number'.--------------------------------------------------------------------3. addNumber(5,5)// return 10
That is do this all you have read .
Now let’s create a function which takes two argument as type string then concat two string and return the length of the string in Typescript.
Let’s play with what you have learned , meet you at part 3.