JavaScript, as you know, is a weakly typed language. While this feature allows you to write a code easily and freely, it also make the language prone to logic error whick is very hard to find. TypeScript is a superset of JavaScript. It includes all the features from JavaScript and has an additional feature, yep! you guessed right: type checking which makes it easier to find logic errors early in the development process.
One cool thing about TypeScript is that the additional type safety does not interfere with how the original application works meaning that even if you see errors regarding types it won't effect whether or not your application will run.
Installation
For the browser to identify TypeScript. The file should be compiled to a JavaScript file. We need a compiler for this and you can download here(https://www.typescriptlang.org/).
Click the 'try' button. There are two ways you can try TypeScript.
1. Playground
This is a online playground for TypeScript (no installation needed).
2. Setting Up Locally (NPM)
You can use package managers (npm, yarm, pmpm) to install TypeScript on your machine. Create a folder and open a code editor of your choice. Run the command below (here I am using npm).
npm install typescript --save-dev
After installation, you will see a TypeScript folder.
Compliation
Create a TypeScript file with a '.ts' extension.
First, let's see how we can complie a TypeScript file to a JavaScript file. Copy and paste the code below (or similar) in the TypeScript file.
// practice.ts
function addNumbers(num1, num2) {
console.log(num1 + num2)
const result = num1 + num2
return result
}
document.body.innerHTML = addNumbers(1, 2)
Run the command below. npx is one of the commands of npm. It is used to use commands outside the scope of npm command. tsc is TypeScript complie command.
※ For you information, if you set up the TypeScript globally on your machine with '-g', you can just run tsc without the npx command.
npx tsc fileName
After compliation, you will see a JavaScript file created.
Type Check
As mensioned above, one of the main reasons of using TypeScript to enforce type checking early in the development phase to prevent errors. Let's how it works.
Take look at the JavaScript code below, you will notice that I have added a string and a number type to a function which seems to expecting numbers to add them and return the result. Depending on the situation, this might be your desired functionality but most of the time this might be a mistake.
As the result returned will be a string contactinated from the two values not the sum of them.
1. Typing
You can specify any type (A return value of a function, Object, Array,...). The format is variableName : type.
let string: string
let number: number
let boolean: boolean
let nullValue: null
let anything:any
★ Type 'any' is a wildcard provided by the TypeScript language itself. It allows any type not just a certain type. It is recommanded to use this wildcard type only when it is neccessary as it can defeat the purpose of using TypeScript.
2. Type inferrence
TypeScript is quite smart, it can infer desired type automatically when it is obvious even if we don't specify the type.
let stringInferred = 'string'
let numberInferred = 1
let booleanInferred = true
let nullValueInferred = ''
Type inferrence can get messy when there are more than one possible type. For example, empty string ('') can also be translated to a null type so if you initiate a variable with '' you won't be able to add a string to the variable as null and string are two different types.
let nullValueInferred = ''
If you dig deeper on this matter, this kind of behavior also happens when the value returned is an empty string. This will throw an error so we need a way to get around this. There sevaral ways to solve this problem.
▶ Any
First option is to use 'any' type. But again, this is not the best solution as it can defeat the purpose of using TypeScript.
▶ Union
Second option is to specify multiple types using a or operator ('|'). This is called a 'union' type
let nullValueInferred: string | null
▶ Casing
The third option is to use the casing. In TypeScript you can case a type to a different type by appending 'as' and the desired type.
nullValueInferred as string
3. Typing Array, Object
▶ Array
An array uses square braket to specify that it is an array
let array: string[] = []
let arrayInferred = ['string'] // string[]
let arrayInferred = ['string', 0] // (string | number)[]
let arrayInferred = [] // any[]
let array: string[] | number[] = []
▶ Object
Attributes you add to an object are required by defaul so you cannot omit a value. If you want to omit a value for a certain attribute, use '?' to make it optional (You can also use interface if you don't want your code look messy).
let object: { name: string; age: number; married?: boolean } = {
name: 'tom',
age: 20,
}
let objectInferred = {string:'string', number:0}
▶ Array of an object
let arrayOfObject: {}[] = []
4. Type Checking
Now let's see how type checking can improve our code. Add types to each parameters.
function addNumbers(num1:number, num2:number) {
console.log(num1 + num2)
const result = num1 + num2
return result
}
document.body.innerHTML = addNumbers('1', 2).toString()
Then you will see a error message right after. Let's try to compile the file so see how this effects our application.
Even though you see the errors,
it compiled and created a JavaScript file. This proves that the type safety feature does not effect whether the application will run or not.
※ If you want your app not run at all when there is a type error. You can add an option to do so like below.
npx tsc --noEmitOnError practice.ts
Let's try to compile again with this option. As you can see it was not compiled to '.js' file.
Now, let's provide a proper type to each parameters and complie again.
Then you will see the created JavaScript file (ECMAScript)
In this writing, we explored TypeScript and hope you enjoyed it.
Source Code
https://github.com/jin-co/web-mobile/tree/master/TypeScript
GitHub - jin-co/web-mobile
Contribute to jin-co/web-mobile development by creating an account on GitHub.
github.com
References
https://www.typescriptlang.org/
JavaScript With Syntax For Types.
TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.
www.typescriptlang.org
'Frontend > TypeScript' 카테고리의 다른 글
Generic (9) | 2023.05.12 |
---|---|
Decorator (3) | 2023.05.12 |
Interface (0) | 2023.03.06 |