Write it up front

  • Problems and simple solutions for getting started with typescript.

Q&A

1. Do all variables need type annotations?

  • In this case, in principle, we want to annotate all values with type annotations.

  • For the TS compiler, if the variable is declared without type annotations, TS automatically deduces the variable type from the assignment. This is perfect and convenient most of the time, but there are a few exceptions:

  • Different types of values are then assigned

When you later need to reassign the variable to another type, TS will give you an error because it is not the type that TS originally derived.

let a = 1;
a= 'string'; // error!
 

let obj = {
    name: 'John'
}
obj.age = 20; // error!
obj.name = 250; // error!
 
 
// better
let a: string | number = 1;
a = 'string'; // ok
 
 
let obj: {
    name: string | number; age? : number; } = {name: 'John'
}
obj.age = 20; // ok
obj.name = 250; // ok

Copy the code

Initial assignment is not an explicit value

That is, the current TS does not know the type of the value, such as a value returned from a back-end interface, or from other functions that are explicitly declared types, etc. That is, if there is no initialization or TS cannot deduce the type from the initialized value, the default type is any.

2. We define the parameter values of the interface when pairing the interface

  • No errors are reported in this case, but you lose type checking and code hints. In this case, it is best to add type declarations and annotations.
// normal
http.get('/api')
    .then(resp => {
        let data = resp; // data: any
    });
 
 
// good one
interface IResponse {
    code: number;
    data: IUser;
}
 
 
http.get('/api')
    .then(resp => {
        let data: IResponse = resp; // data: any
 
    });
Copy the code

In both cases, you need to define the type in advance and add type annotations. Otherwise, we encourage, but do not require, the addition of type annotations. For the most part, TS does a good job of automatically identifying the type when we initialize the assignment, and we can also get the typeof the value through typeof. Kill two birds with one stone!

3, use opportunelytypeDefine the type of


// good one
let user = {
    name: 'Lucy'.age: 20
}
type User = typeof user;
 
 
// deprecate
type User = {
    name: string;
    age: number;
};
let user: User = {
    name: 'Lucy'.age: 20'}Copy the code

In the first way, when we declare the user variable, we get both the value and the type! Conversely, the second way is a bit wordy.

4, using TS to rewrite the current code encountered various errors?

  • There are no errors in object properties:

This is typically the case where the object value TS knows that it has an explicit type (not any; if it were any, there would be no error), but the property currently being accessed does not have a structure of its known type. There are two ways to solve this problem: – If you can change the type declaration of the value, add the attribute of the missing value; – otherwise, use the // @ts-ignore annotation, or use type assertion, enforce any :(this.props as any).notexists

  • Type unclear error:

That is, the type of a value may be annotated as a union type, and when accessed directly, TS cannot determine which exact type the current value belongs to, so it will report an error. This situation has the following solutions to bibimbap:

- Use type Guards - Use type assertions - use the // @ts-ignore commentCopy the code

Type protection should be a priority because it is essentially adding code logic to help TS understand and determine the current type, so the code is more robust. The latter two methods, unless it is clear that the value is the definite type at this time, are still likely to fail at the code execution stage, even if the TS compiler is passed!

  • Error in which the value may not exist or is undefined:

    • This is actually one of the type ambiguity errors mentioned above, usually with optional attributes or optional parameters. The easiest way to resolve these cases is to use a non-null type assertion (provided that the value is indeed non-null) :

    • Non-null type assertions take the form of a half-angle exclamation point after a value:

someVar! .toString();Copy the code