Typescript Just getting started

Daniel Cooper
2 min readNov 16, 2020

--

I’m new to typescript this is what I’ve learned so far enjoy.

What is TypeScript?

TypeScript is basically Strongly typed or Statically typed JavaScript. It can do all the things javaScript can do with the addition of it being Strongtyped. This means whenever we assign a variable they are not locked to that dataType. So if I do (let dog = “ dog”) then dog now a string and can only be a string. Now there are ways to get around it but we get to that in a bit.

let dog = "dog";
^ type = string

Defining types

There are two ways to define a type explicitly and implicitly. To Implicitly define a type all you need to do is declare and assign a variable like normal. Typescript knows the types of the variable you assigned so our dog variable from above would be a string. Now that dog is defined as a string you can only reassign dog to string and no other types.

//Another example of Implicit
let Danny = 21;
^ type = number

Now to explicitly define a type you use the (: type) syntax this will set the variable to whatever type you used. (an example will be shown below.) So if have an initial variable in mind you should use the Implicit way. But say you know this variable is going to be a boolean but you don’t want it to start off as true or false then you can assign the variable a type and then, later on, assign it to true or false.

let name: string;
^type = string
let age: number;
^type = number
let x: any;
^type = any type
let x;
^ = : any
let dog: string = "dog"
^type = string
// if you are going to assign something to the variable you don't need to do the :string

Creating types

When using Typescript you can create more complex types by fusing simpler ones. There are two common ways to do this with Unions or Generics. When you use Union you can declare that a type can be multiple different types. A lot of the time This is used a lot to describe a set of string or numbers. When using Generics you can assign a variable to a type. The most common example I found was for an array. So normal an array can have anything it wants inside but with Generics we can say this is an array of string or array of numbers.

//Unions
type MealSate = "breakfast" | "Lunch" | "Dinner"
//Generics
type NumberArray = Array<number>
typeObjectWithAgeArray = Array<{age: number}>

TypeScript is something new to me that I’m enjoying and find interesting I can’t wait to learn more about it on the project I’m working on. Typsric is a pretty big topic I hope this blog helped you learn something or helps you in any way. I will post some links on typescript I’m finding really useful below.

Helpful Links

--

--

No responses yet