When writing TypeScript code, you type your variables with a colon :
followed by the type.
Simple types
Here’s the syntax:
let name: string;
Here, we say the name
variable has a string type. Which means, you can only assign values of that type to the variable:
let name: string;
name = "deeecode" // fine
namee = "typescript" // fine
Any attempt to assign something else to this type, you get a TypeScript error:
let name: string;
/**/name/**/ = true
Type 'boolean' is not assignable to type 'string'. Typing function parameters
You can also type function parameters:
function sum(num1: number, num2: number) {
return num1 + num2
}
Now when you pass a different type, you get an error:
function sum(num1: number, num2: number) {
return num1 + num2
}
sum(10, /**/"50"/**/)
Argument of type 'string' is not assignable to parameter of type 'number'. Here, "50"
is not a number and num2
is expected to be a number.
You can also type an array of items like this:
function sum(nums: number[]) {
return nums.reduce((a, b) => a + b)
}
sum([2, 10, 100, /**/"hello"/**/])
Type 'string' is not assignable to type 'number'. Here, we type nums
to be “an array of numbers”. When we pass a string in the array, we get an error.
Return type of Function
You can also type the returned value of a function:
function sum(nums: number[]): number {
return nums.reduce((a, b) => a + b)
}
sum([2, 10, 100])
By having : number
after the parentheses, you specify the type of value that this function would return when called.
Also, with an arrow function:
function sum(nums: number[]): number {
return nums.reduce((a, b) => a + b)
}
sum([2, 10, 100])
There are many more types you can use.