Array scenario 5
There are all kinds of things in my numbers. What should I do? As the old rule, first write your data according to JS. (Union type)
To analyze the data, just add the colon of arr
Before you finish typing the code, vscode has started to remind you how to write it. Just use|
This operator actually has the same meaning as JSLogical or||
The principle of operator is the same And the type must be in()
Internal writing.
I can’t even copy, so I can’t help it
Don’t forget that this is an array of data. Add []
Array scenario 5
What does it mean if I don’t add parentheses?
You will understand if I write it like this.
Removing the parentheses means that each type is used to constrain the ARR variable, which specifies that arry is eitherstring
Array of type, ornumber
Array of type. Equivalent to each|
What is separated is a single individual.
III Function format writing
Function scenarios one
In fact, there are some differences here, but it doesn’t matter. You still write it according to the mechanism of your JS code. All variable types are given to any first
At this time, although your code is expected to achieve the sum of two numbers, others may understand your code as the addition of two strings. As shown in the following figure, there will be no error.
So here we need to clearly tell others that it is also to review our own code in the future so that it will not seem like we are looking at a pile of shit.
By the way, don’t forget to constrain the return value. Add () after function:
Specify the return value type.
Function scenario 2 Arrow function (determined that the parameter is number, and the return value is also number)
How do we set the parameters? The truth is the same.
Function scenario 3 The return value of the function is null
If you expect a function to be a simple logical operation without a return value, you can setvoid
Properties,void
The English word means null, and in TS means returnundefined
, that is, there should be no return value.
Function scenario 4 Optional arguments to function
Assuming I don’t know whether the first parameter has a value, it is specified in the TS that optional parameters are not allowed to appear before the required parameters.
Then we debug it. In fact, we can see that,?
It means
b:number | undefined
It has the same meaning as the previous logical or.
Summary: adding types to functions in TS basically means adding types to parameters and return values.