TypeScript is a typing language that is almost like a subset of JavaScript. What is a typing language? Languages such as Java and C++ are known as typing langauges because you declare the variable type when initialising it. In this post I will give a brief introduction and a few examples of how you can apply TypeScript to your code.
There are two distinct features of TypeScript which will be covered in this post, Object Oriented Programming
and Strong Typed Variables
.
You will need to have node.js
installed on your machine. If you donβt have this installed go here.
To install TypeScript you are going to need to type the following command into your terminal npm install typescript
.
You will need a transpiler (a popular one is Babel) for your code to be translated into normal JavaScript code. If you are using React, you will use the file extension .jsx
.
If you would like to transpile a single TypeScript file you can use the following command in your terminal: tsc <your-file-name>.ts
and the file extension will be .ts
.
let aTest: boolean = true
let decimal: number = 10
let hex: number = 0xF00F
let binary: number = 0101
let test: string = "test"
let name: string = `your name`
let age: number = 20
let list: number[] = [2, 4, 6]
let list: Array<number> = [2,4,6]
let anyTest: any = 4 //any refers to any type of variable
anyTest = "could change to a string"
let aString: any = "an example"
let aStringLen: number = (<string>aString).length
let aStringLeng: number = (aString as string).length //when using TypeScript with JSX only as assertions are allowed
public: allow access from outside of the class
private: no access allowed from outside of the class
protected: can only be accessed within the class
class Cat {
private name: String;
private age: number;
constructor(name?: string, age?: number) {
this.name = name;
this.age = age;
}
}
let cat = new Cat();