Do you really understand TypeScript?

Next, I want to introduce an amazing feature. I dare say that 99.9% of people who master TypeScript don't know this feature. When you master this feature, you will find it is useless, but when you realize this feature , you will feel that you do not understand TypeScript.

Are you ready? The next thing that will destroy Sanguan is coming, look at the real code below: source link

const isString = (val: unknown): val is string => typeof val === 'string';

If you only look at the JS part of the above code, I believe any basic developer can understand it, not just front-end developers, but after adding the type, you may have a question mark in your heart?

val is string, what is this, why haven't I seen it, is this really the TS I'm learning? Did I learn fake TS? What kind of grammatical work is this?

In fact, this grammar is not only the content of TS but also used in practice

This syntax belongs to the TS type protection mechanism . There is also a proper noun called type predicate , which can narrow the type of function parameters. Combined with the above example, let's explain its mechanism of action.

First of all, the isString function, its parameters are uncertain, how do we limit the incoming parameters to be strings? This can be achieved through type constraints.

The position of the type constraint is defined in the return type position of the function. Before is, it must be a parameter of the function, and after is is the type of the parameter.

In addition, it can also be applied in another place, that is, the method of the class, using this in the is constraint method.

image.png

Is this syntax useful? Don't use it, why not use it, it's very tasteless, because after the constraint is used in some cases, it is necessary to use as in the function body:

interface Bird {}
interface Fish {
    swim: () => void
}
function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

And basically you can’t understand it. If you don’t read ta’s documentation, even if you learn it, it’s best to forget it. Most of the time, just omit the type and you can understand what the code is written.

Guess you like

Origin juejin.im/post/7255628830131896376