Ultimate Guide to Types in TypeScript
Typescript is a strongly typed language. In this guide we'll be showing you everything you need to know about how to use types in Typescript
Join the DZone community and get the full member experience.
Join For FreeTypeScript is a strongly typed language built on top of Javascript. As such, types have to be defined in TypeScript when we write our code, rather than inferred as they normally are in Javascript.
In this guide, we'll be diving into how types work in TypeScript, and how you can make the most of them. If you're totally new to TypeScript, start with our guide on making your first TypeScript project.
The Fundamental Types in TypeScript
Javascript has a number of different types. If you want to learn about how types work in Javascript, read our guide here. In this guide, we'll be covering the main types you can use in TypeScript. An understanding of Javascript types will be useful, but for simplicity, below is a list the most fundamental TypeScript types you will see the most:
undefined
- when something is not defined in the code, or does not exist.any
- refers to any type - essentially not enforcing a type at all.enum
- an enum - see here for more on enums.number
- a number between -2^53 - 1 and 2^53 - 1, i.e. 1.string
- a combination of characters i.e. test.boolean
- true or false.bigint
- a number bigger than 253 - 1.symbol
- a completely unique identifier.function
- self-explanatory - a function.object
- an object or arraynever
- used in functions - for when a function never returns a value, and only throws an error.void
- used in functions - for when a function never returns a value.
Custom Types in TypeScript
TypeScript also allows us to define our own custom types. You can learn about that here.
Fundamentals of Types in TypeScript
Now that we've outlined all the fundamental types that TypeScript uses, let's take a look at how they work. First, let's start with syntax basics.
Using TypeScript Types in Variables
The syntax of types on variables in TypeScript is relatively straight forward. If we expect a variable to be of a specific type, we define it after a colon, after the variable name. For example, the below variable is defined as having type number.
let x:number = 5;
Similarly, a string type might look like this:
let x:string = "Some String";
If you do not define the type of a variable properly, TypeScript will throw an error. For example, let x:string = 5 would throw the following error:
Type 'number' is not assignable to type 'string'.
Defining Object Types in TypeScript
Objects are everywhere in Javascript, and it's no different in TypeScript. An object in TypeScript is of type object, but values inside an object also have their own types. In the most basic example, we can define a variable as type object, which refers to an object of any length or value set:
let myObject:object = { a: 1 };
If we want to get a little more complicated, we can also define the expected types of properties within an object. Suppose we have an object where we have 3 properties:
name
, of typestring
age
, of typenumber
interests
, of typeobject
, where interests is optional We can define each of these explicitly, using the following format:
let userOne:{ name: string, age: number, interests?: object } = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };
As you might notice, this is becoming a little messy! Often, when we do this, we'll create custom types. As an example, here is the same code using a custom type instead:
type User = {
name: string,
age: number,
interests?: object
}
let userOne:User = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };
Now we have a nice clean User type that we can apply to any variable or function. Next, let's look at arrays.
Defining Array Types in TypeScript
Since Arrays and Objects can contain their own types within, how we define them is slightly different. For arrays, the most basic way to define the type is to use the type[] syntax. For example, an array of strings looks like this:
let arrayOfStrings:string[] = [ 'some', 'strings' ];
Here, string can be replaced with any other valid type. If we know the exact number and types of elements that will appear in our array, we can define it like this:
let myArray:[ string, number ] = [ "some", 15 ]
In TypeScript, when we define an array like this, with fixed types and a fixed length, it is known as a Tuple.
Mixed Array Types in TypeScript
Sometimes, an array may be made of multiple types, but have an unknown length. In this situation, we can use a union type. For instance, an array of unknown length which only consists of strings and numbers, looks could be defined as this:
let myArray:(string|number)[] = [ "some", 15 ]
Again, for more complicated types, though, we may want to define our own types.
Using TypeScript Types in Functions
The same principles ultimately apply to functions - the only difference here being that a function also often has a return value. Let's start by looking at a simple example without a return function. Notice that we define the type of each argument in the function:
function generateName(firstName: string, lastName: string) {
console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John", "Doe");
This function will run successfully, since we've given the right types when we ran the function (i.e. both arguments are strings).
One fundamental difference between TypeScript and Javascript, is that if we were to run generateName("John");
, TypeScript would give us the following error:
Expected 2 arguments, but got 1.
Since TypeScript is far more strict than Javascript, it was expecting two arguments - not one. If we want this to work, we have to explicitly tell TypeScript that argument two is optional. We can do this by adding a ? after the second argument. As such, the following code works fine, with no errors:
function generateName(firstName: string, lastName?: string) {
console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John");
Using TypeScript in Functions with Return Types
Adding a return type in TypeScript is straightforward. If a function returns something using the keyword return, we can enforce what type the data from return should be. Since we are returning nothing - so our return type is known as void.
If we want to add our return type to this function, we use the same :, so our code looks like this:
// Note that we have added : void!
function generateName(firstName: string, lastName: string): void {
console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John", "Doe");
Now TypeScript knows that this function will only ever return nothing. If it starts to return something, TypeScript will throw an error:
Type 'string' is not assignable to type 'void'.
As such, TypeScript helps protect us from unknown pieces of code trying to return data in functions. Let's suppose we want to change our function to return, rather than console.log. Since our return will be of type string, we simply change our function's return type to string:
function generateName(firstName: string, lastName: string): string {
return `Hello ${firstName} ${lastName}`;
}
// Run the function
let firstUser = generateName("John", "Doe");
Writing Functions as Variables in TypeScript
Javascript has a common notation where functions are written as variables. In TypeScript, we can do the same, we just have to define the types up front. If we wanted to convert our function above to the variable format, it would look like this:
let generateName:(firstName: string, lastName: string) => string = function(firstName, lastName) {
return `Hello ${firstName} ${lastName}`;
}
Notice one small difference here, is that the return type is after =>
, rather than :
. Also note, that we did not define types for firstName
or lastName
in the function()
itself - this is because we defined them as part of the variable - so no need to do so again.
Conclusion
After this, you should have a good understanding of how types work in TypeScript. In this article, we have covered:
- The fundamental and most common TypeScript types
- How to define variable and function types in TypeScript
- How to set the return type of a function in TypeScript
- Creating basic custom types for objects in TypeScript
- How to create array and tuple types in TypeScript
I hope you've enjoyed this introduction to TypeScript types. You can find more TypeScript content here.
Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments