What can typescript helps?
- Static type-checking
Check type error before running the code
const rabbit = 'yuan yuan';
rabbit();
- Non-exception Failures
- Call an undefined property
- typo
- uncalled function
- basic logic errors
const rabbit = {
name: 'yuan yuan',
age: () => 10
}
rabbit.habit;
rabbit.nama;
rabbit.age < 10;
const rabbitName = rabbit.name === 'yuan yuan' ? 'yuan yuan' : 'nii'
if (rabbitName !== 'yuan yuan') {
} else if (rabbitName === 'nii') {
}
- Types for Tooling
- suggest which properties you might want to use
- deliver “quick fixes” to automatically fix errors
- jump to definitions of a variable
- find all references to a given variable
How to use
npm install -g typescript
- Create a file
hello.ts
and run tsc hello.ts
you will find out there is a new file created - hello.js
this is a plain javascript file complies / transforms by tsc
.
console.log('test')
- Try to create some errors and you can see the error in command line
function rabbit(name, age) {
console.log(`${name} is ${age} age old!`);
}
rabbit("yuan yuan");
Explicit Types
- Add type annotation on the properties
function rabbit(name: string, age: number) {
console.log(`${name} is ${age} years old!`);
}
- Before we add annotation, we can not tell what type of value we should pass in.
- After having type annotation, when we hover on the function we can see the type of properties.
- And this is what we have after compiled
Others
- Downleveling - rewrite code from newer versions of ECMAScript to older ones
- Strictness - there are different level of strictness can be set up in
tsconfig.json
noImplicitAny
- will issue an error on any variables whose type is implicitly inferred as any
strictNullChecks
- makes handling null
and undefined
more explicit
Reference