TS self-study course (1) - strong type and weak type

Get into the habit of writing together! This is the 10th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

type

If you search Wikipedia for the definition of the word type, you will find: Types exist in every field.

In computers, however, types identify a value or set of values ​​with a specific meaning and purpose (although some types, such as abstract types and function types, may not be represented as values ​​during program execution).

People familiar with a little programming know that "HelloWorld" is a string type, 1234 is a number type, and true is a boolean type.

Types are the foundation of programming. JS has types, and so does other programming.

Collections of types in the JavaScript language consist of primitive values ​​and objects .

Concepts derived from types that need special attention include:

A type system is used to define how values ​​and expressions in a programming language are classified into many different types , how these types are manipulated, and how these types interact.

The verification process performed by type checking and the enforcement of type constraints can occur at compile time (static checking) or at runtime (dynamic checking). Static type checking is performed in the semantic analysis performed by the compiler . If a language enforces type rules (that is, usually only automatic type conversions are allowed on the premise that no information is lost) the process is called strong typing , otherwise it is called weak typing .

weakly typed

Like VB, PHP, JavaScript are weakly typed languages, to create a property or variable, even if a value of a certain type is assigned, we can still switch types at runtime.

let userName='搞前端的半夏'

userName=123
复制代码

Strong typing

Like Java, Python, and C++ are strongly typed languages. When a variable is defined, the type of the variable is specified.

int userName='搞前端的半夏'
复制代码

Once a variable's type is determined, it will always be that data type unless it is casted.

TS is strongly typed, once we assign a value of a specific type to a created variable, TypeScript requires us that the variable's value remains typed.

For the above code, we rewrite it in TS:

let userName:string='搞前端的半夏'
userName=123
复制代码

An error will be reported in the TS environment:

image-20220406232626995

At the same time you will find:

Weakly typed languages ​​do not explicitly specify the type of a variable when declaring a variable

Strongly typed languages ​​must specify the type of the variable, just as in C language we want to define a variable of type number, we must use int or float:

float f,x=3.6,y=5.2;
int i=4,a,b;
复制代码

Guess you like

Origin juejin.im/post/7085736602693009415