Typescript - The basics
更新時間: 2023/04/02
What can typescript helps?
- Static type-checking Check type error before running the code
const rabbit = 'yuan yuan';
rabbit();
// This expression is not callable.
// Type 'String' has no call signatures.
- Non-exception Failures
- Call an undefined property
- typo
- uncalled function
- basic logic errors
const rabbit = {
name: 'yuan yuan',
age: () => 10
}
rabbit.habit;
// Property 'habit' does not exist on type '{ name: string; ';}.
rabbit.nama;
// Property 'nama' does not exist on type '{ name: string; ';}.
rabbit.age < 10;
// Operator '<' cannot be applied to types '() => number' and 'number'.
const rabbitName = rabbit.name === 'yuan yuan' ? 'yuan yuan' : 'nii'
if (rabbitName !== 'yuan yuan') {
// ...
} else if (rabbitName === 'nii') {
// This comparison appears to be unintentional because the types '"yuan yuan"' and '"nii"' have no overlap.
}
- 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
- Install
npm install -g typescript
- Create a file
hello.tsand runtsc hello.tsyou will find out there is a new file created -hello.jsthis is a plain javascript file complies / transforms bytsc.
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.jsonnoImplicitAny- will issue an error on any variables whose type is implicitly inferred asanystrictNullChecks- makes handlingnullandundefinedmore explicit