“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

preface

Earlier we introduced the types in TS:

  1. In TS, the corresponding data type is JS
  2. Compared with JS, TS has more types

Today we’ll clarify two concepts in TS: type assertion and type guard

example

Let’s start with an example

type User = {
    name: string;
    age: number;
}
function showUser(user: User) {
    console.log(user.name);
    console.log(user.age);
}
showUser({ name: 'Alice'.age: 12 })
Copy the code

As shown above, the showUser function executes arguments that are type-compliant. However, an error is reported if the parameters do not meet the requirements

let errorType = ' ';
showUser(errorType); / / error
Copy the code

Normally written code would not cause this problem, but the data could come from somewhere else at run time (such as a database, third-party libraries, user input, and so on).

We know that languages do not have types at runtime, so how do we ensure and verify that data from elsewhere meets our requirements at runtime?

That’s what type assertions do

Types of assertions

The so-called assertion is to conclude, certain, absolute meaning; So simply put, a type assertion is a guarantee that the data type must be the required type

Type the guards

Type assertions also require the help of a type-guard function, which is used to determine whether unknown data is of the desired type

function isUser(arg: any) :arg is User {
    if(! arg) {return false;
    }
    else {
        if (typeof arg.name == 'string' && typeof arg.age == 'number') {
            return true;
        } else {
            return false; }}}Copy the code

As you can see, a type-guard function is not much different from a normal function, except that its return value is of a special type: x is y, indicating whether x is of type Y

if (isUser(errorType)) {
    showUser(errorType);
}
Copy the code

No error is reported after such a type assertion

END

That’s all for this article