# 3 Advanced TypeScript features

When it comes to TypeScript, there are three features I wanted to share with you that I found pretty cool.

For my examples, I used [TypeScript Playground](https://www.typescriptlang.org/play).

# Conditional Types

Conditional types were something I found extremely cool, being able to conditionally return a type, I actually found it hard to learn due to misunderstanding the term `extends` in this context.

Let's have a look at a simple example:

![Conditonal types example](https://cdn.hashnode.com/res/hashnode/image/upload/v1624510031590/6cA60vzD5.png)

Here all we are saying is, if `Dog` is of type `object`, if it contains that, then we want the type `NumberOrString` to be a number, otherwise, if that wouldn't be the case for some reason, then we want the type to be a string.

[Here you can read more on conditional types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html).

# Template Literal Types

Template Literal Types are just the pure definition of flexibility, I was actually astonished when I learned about them 😄.

Let's say we want to define some CSS values, and we want developers to only be able to pass `px` or `rem` values, then we can do something like this:

![Template literal types example](https://cdn.hashnode.com/res/hashnode/image/upload/v1624510564507/OFWnDCVss.png)

Here we have two correct variables and one which is false, the one TypeScript complains about. The variables with the type `Value` must explicitly have a number and unit of either `px` or `rem`.

[Here you can read more on template literal types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html).

# Asserts

Let's say we have a simple function, `arrayOfNumbers`, that returns an array of numbers with the given inputs, but the type of the inputs is `unknown`.

![TypeScript sample without assert function](https://cdn.hashnode.com/res/hashnode/image/upload/v1624511726532/6prN8Y_Mh.png)

Using `asserts` of TypeScript we can create a function that we can invoke inside of `arrayOfNumbers`, in order to ensure the inputs are of type number, that way TypeScript won't complain anymore.

![TypeScript sample with assert function](https://cdn.hashnode.com/res/hashnode/image/upload/v1624512134874/DOSrDNM7A.png)

Now the function `arrayOfNumbers` doesn't complain, because using our `assertIsNumber` function, we ensure the inputs of the function are of type number, otherwise, we throw an error if that is not the case.

We created a function which asserts that the inputs are of type number, but you can do the same with type string, boolean and other types 😁.

Here you can find more examples of [assert functions](https://www.typescriptlang.org/play#example/assertion-functions).
