You can create simple to advanced types with TypeScript. We’ve seen the string
type, but let’s learn about more basic types.
number
let num1: number = 20
/**/num1/**/ = true
Type 'boolean' is not assignable to type 'number'. boolean
let isRaining: boolean = true
/**/isRaining/**/ = "false"
Type 'string' is not assignable to type 'boolean'. arrays
We can declare an array of string
s like this:
let fruits: string[] = ["mango", "orange", "strawberry"]
fruits.push(/**/20/**/)
Argument of type 'number' is not assignable to parameter of type 'string'. And an array of number
s like this:
let numbers: number[] = [20, 40, 60]
numbers.push(/**/"hello"/**/)
Argument of type 'string' is not assignable to parameter of type 'number'. There’s also the Array
type we can use like this:
let fruits: Array<string> = ["mango", "orange", "strawberry"]
fruits.push(/**/20/**/)
Argument of type 'number' is not assignable to parameter of type 'string'. Here we are using the Array
generic type. Don’t worry about this now. We’ll learn about generic types later.
tuples
Tuples are like arrays but with a fixed number of elements which are also typed. Here’s an example tuple:
let tuple: [string, number] = ["hello", 50]
tuple[/**/2/**/]
Tuple type '[string, number]' of length '2' has no element at index '2'. As you see above, trying to access an index not in the fixed length throws an error.
let tuple: [string, number] = ["hello", 50]
/**/tuple[0]/**/ = 20
Type 'number' is not assignable to type 'string'. From the above example, we assigned the 0
index to string
so putting a number
there throws an error.
undefined
let user: undefined = undefined
/**/user/**/ = {
name: "deeecode"
}
Type '{ name: string; }' is not assignable to type 'undefined'. object
You can also create an object type:
let user: {
name: string;
age: number;
isLoggedIn: boolean
} = {
name: "deeecode",
age: 40,
isLoggedIn: true
}
user./**/something/**/ = "hello"
Property 'something' does not exist on type '{ name: string; age: number; isLoggedIn: boolean; }' Our type does not include a something
field, so trying to add that field throws an error.
Looking at our object type, it’s possible that we want one of the fields to be optional. Maybe we don’t want the age
field to be required. For that, we can use a question mark before the colon ?:
:
let user: {
name: string;
age?: number;
isLoggedIn: boolean
} = {
name: "deeecode",
isLoggedIn: true
}
Since age
is optional, we do not need to pass it.
We’ll learn about more ways we can type variables in the coming lessons.