“This is the 39th day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
Now that you know the basics of TypeScript, it’s time to learn about variable declarations.
Declaring multidimensional arrays
Suppose there is a statement like this:
let arr3: number[] [] [].Copy the code
To know the specific type of ARR3, its analysis steps are as follows:
As you can see, the type disassembly is from right to left, corresponding to the value of the specific variable is from the outside to the inside layer of disassembly.
Just to give you an example, someone with a little experience can tell at a glance that ARR3 is a three-dimensional array. However, teaching people to fish is better than teaching them to fish, and this analysis method is suitable for most complex data types analysis.
Property renaming
With ES6’s destructuring assignment, we can declare variables like this:
let personInfo1 = {
name: Programming Samadhi.age:22
}
let {name: nameP, age: ageP} = personalInfo1;
Copy the code
The above code declares nameP and ageP variables. Note that in variable declarations, the colon is not followed by the data type, but by the new declaration to replace the value of the property of the original object.
To specify nameP and ageP data types in TypeScript, write:
let { name: nameP, age: ageP }: { name: string; age: number } = personInfo1;
Copy the code
This type specifies the type that can be placed in the object declaration, specifying the value of each attribute of the object:
let personInfo1: { name: string; age: number } = {
name: Programming Samadhi.age: 22
};
personInfo1.name = 12; // Error cannot assign type "number" to type "string"
// let {name: nameP, age: ageP} = personInfo1;
let { name: nameP, age: ageP } = personInfo1;
nameP = 12; // Error cannot assign type "number" to type "string"
Copy the code
Let and const temporary dead zones
The following code does not report an error in TypeScript, but does report an error in real execution.
function foo() :number {
return a1;
}
foo();
let a1: number = 12;
Copy the code
Actual operation error:
My own understanding is that static compile time checks only for data type correctness, while dynamic runtime checks only for syntax and logic errors, and temporary dead zones occur at run time.
conclusion
These are the notes and summaries I documented while learning about TypeScript variable declarations.
~
Thanks for reading!
~
Learn interesting knowledge, meet interesting friends, shape interesting soul!
Hello everyone, I am the author of “programming Samadhi”, I am king Yi, my public account is “programming Samadhi”, welcome to pay attention, I hope you can give me more advice!