TypeScript series type null

Memories of sentences


TypeScriptThe type in nullrefers to nullthe type of value that the variable can store. nullValue means that the variable has no value or is undefined. It is JavaScripta special data type in and represents a null value or a non-existent object reference.

In TypeScript, we can specify nullthe type for the variable, for example:

let myVar: null;

At this time, myVar can only store nullvalues ​​and cannot store other types of values, otherwise an error will be reported.

Using nulltypes can prevent variables from being misused when they are undefined or have no value, thereby improving the reliability and safety of your code.

Here is an nullexample using the type, which defines a variable name that defaults to null when not assigned a value:

let name: string | null = null;

function printName() {
    
    
	if (name === null) {
    
    
		// 判断变量是否为 null
		console.log("Name is not defined.");
	} else {
    
    
		console.log(name);
	}
}

name = "pidancode.com";
printName(); // 输出 pidancode.com

name = null;
printName(); // 输出 Name is not defined.

In the above example, we first define a variable name, which is of type string or null. Then a printName function is defined to output the value of the variable.

The if statement is used in the function to determine whether the variable is null. If so, a prompt message is output, otherwise the value of the variable is output.

In the first call to the printName function, we assign name to the string pidancode.com and output the string. In the second call, we assign name to null, and the prompt message Name is not defined. is output.

This example shows how to use the null type to determine whether a variable has a value, which avoids the possibility of misuse of variables and improves the reliability and security of the code.

write at the end

If you feel that the article is not very good //(ㄒoㄒ)//, just leave a message in the comments and the author will continue to improve it; o_O???
if you think the article is a little useful, you can give the author a like; \\*^o^*//
if you want to make progress with the author, you can scan the QR code on WeChat , pay attention to the front-end old L ; ~~~///(^v^)\\\~~~
thank you readers (^_^)∠※! ! !

Guess you like

Origin blog.csdn.net/weixin_62277266/article/details/133364892