头图

foreword

Knowing the basic types in TypeScript, of course, the next step is to learn about variable declarations.

declare multidimensional array

If there is such a statement:

let arr3: number[][][];

To know the specific type of arr3, the analysis steps are as follows:

image-20220225151900823

It can be seen that type disassembly is from right to left, and corresponding to specific variable values, it is disassembled layer by layer from outside to inside.

Here is just an example, a person with a little experience can tell at a glance that arr3 is a three-dimensional array. However, it is better to teach a man to fish than to give him a fish. This analysis method is suitable for the analysis of most complex data types.

property rename

With ES6's destructuring assignment, we can declare variables like this:

let personInfo1 = {
    name: "编程三昧",
    age:22
}
let {name: nameP, age: ageP} = personalInfo1;

The above code declares two variables nameP and ageP. It should be noted that: in the variable declaration, the colon is not followed by the data type, but the variable declared to replace the value of the original object property.

If in TypeScript, to specify the data types of nameP and ageP, you need to write:

let { name: nameP, age: ageP }: { name: string; age: number } = personInfo1;

In fact, this type specification can be placed in the object declaration, specifying the type of each attribute value of the object:

let personInfo1: { name: string; age: number } = {
    name: "编程三昧",
    age: 22
};

personInfo1.name = 12; // Error 不能将类型“number”分配给类型“string”

// let {name: nameP, age: ageP} = personInfo1;
let { name: nameP, age: ageP } = personInfo1;

nameP = 12; // Error 不能将类型“number”分配给类型“string”

Temporary dead zone for let and const

The following code will not report an error in TypeScript, but it will report an error in actual execution.

function foo(): number {
    return a1;
}
foo();

let a1: number = 12;

Actual operation error:

image-20220225144916570

My own understanding is: static compilation is only responsible for detecting whether the data type is correct, while dynamic runtime detects syntax and logic errors, and it happens that the temporary dead zone is only generated at runtime.

Summarize

These are the notes and summaries that I recorded as I learned about TypeScript variable declarations.

~

~ This article is over, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and shape interesting souls!

Hello everyone, I'm King , the author of 〖 Programming Samadhi 〗, my official account is " Programming Samadhi ", welcome to pay attention, I hope you can give me more advice!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!