[TypeScript] play TypeScript from scratch - data types in TypeScript

Keywords: Javascript Front-end TypeScript

preface

Hello, guys. In the last article, we had a preliminary understanding of typescript: Mastering what typescript is, how to use typescript and when to use typescript. Today we will learn about data types in typescript.

As mentioned in the previous article, TypeScript is a superset of JavaScript. Since it is a superset, some data types in JavaScript must also exist in TypeScript. At the same time, TypeScript as a superset must not only have those data types in JavaScript. What other data types are there besides these data types, Let's dig up the data types in ts.

Data types in TypeScript

TypeScript supports almost the same data types as JavaScript, and extends some other types on this basis. Let's first review the data types in JavaScript, which are also supported by TypeScript:

  • Number: numeric type, whether integer or floating-point, or even binary, octal, decimal and hexadecimal, are all number types
  • String: type of string (text), which can be represented by double quotation marks (") or single quotation marks (') or template string in es6
  • boolean: boolean type, with only two true and false values
  • Null: indicates a null value, which is generally used to release objects referenced by some variables, indicating that variables no longer point to any address
  • Undefined: the default value of all variables without assignment. If a variable only declares that it has no assignment, the default value is undefined
  • Symbol: symbol is a new type in es6 that defines unique values. The values of variables of symbol type are unique.
  • Object: object type (representing non original type) in heap memory
  • Array: array type
  • Function: function type
  • RegExp: regular type

In addition to the common types that typescript and JavaScript share, typescript also extends some other types:

  • Tuple: tuple type, which can be used to represent an array of known data types and lengths. The types in the array are not necessarily the same, but during assignment, the values and types must match one by one, and the length of assignment must be consistent with the length of definition. Otherwise, an error will be reported (an example will be given later)
  • Enum: enum type. Enum type is generally used to define a set of values for developers to use and maintain later. By default, the enum value starts from 0 and the number increases in turn. Of course, we can manually specify its initial value or specify the value we want for each enum. By default, it increases from the initial value (the default value is 0)
  • Any: indicates any type. Sometimes we may not be sure what data type it is. It may be string, number, or any other type. At this time, it can be declared as any type. In fact, this is no different from our usual declaration of JavaScript variables. We can only determine the type of a variable after assignment
  • Void: indicates that there is no type. On the contrary to any, void indicates that there is no type. Generally, a function can be declared as void if it has no return value. If a variable is defined as void, the variable can only be assigned null or undefined. Generally, declaring a variable as void has no meaning.
  • Never: indicates the type of value that will never exist. Never is a subtype of other types. It is generally used for the return value type of a function that always throws exceptions or will never have a return value. For example, if a function always throws exceptions, the return value type of this function can be defined as never

Code demonstration of each data type

  • number
let x: number = 3; //decimal system
let y: number = 0b1010; // Binary
let z: number = 0xf00d // hexadecimal
let a: number = '123' //Error, type 'string' is not assignable to type 'number'
  • string
let str: string = "abc";
let hello: string = 'hello world';
let name: string = `hello: ${str}`
let abc: string= 123 //Error, type 'number' is not assignable to type 'string'
  • boolean
let isTrue: boolean = true;
  • Null type is a subtype of any type, so it can be assigned to any type
let x: number = null;
let y: string = null;
let z: boolean = null;
  • undefined undefined is a subtype of any type similar to null type, so it can be assigned to any type, and variables of undefined and null types can be assigned to each other
let x: number = undefined;
let y: string = undefined;
let z: boolean = undefined;
let a: null = undefined;
let b: undefined = null;
  • symbol unique value type
let x: symbol= Symbol('abc');
let y: symbol = Symbol('abc');;
console.log(x == y); //false
  • Object: object type. All reference data types can be assigned to variables of object type, including null and undefined
let obj: object = {}
let fun: object = function(){}
let arr: object = [];
let reg: object = /^abc/;
  • Array: array type
//There are two ways to declare arrays
// 1. In the form of "data type []"
let arr: string[] =  ['1','2'] //An array of string type. All values in the array must be of string type
// 2. In the form of "array < data type >"
let arrNum:Array<number> = [1, 2] //An array of type number. All elements in the array must be of type number

let arrAny:Array<any> = [1,'2',true]//Array of any type. The elements of the array can be of any type
  • Tuple tuple, tuple is an array with fixed length and type
let arr:[string, number] = ["1", 1];
let arr2:[string, number] = [1,"1"]; //Error reported, type mismatch
let arr3:[string, number] = ["1","1"]; //Error reported, type mismatch
let arr4:[string, number] = ["1",1,true]; //Error reported, length mismatch
  • Enum enumeration type. Enum types are generally used to define a group of values with similar function descriptions or fixed constant values, such as defining a group of color values. The values of enum types are different from other types, and enum types need to be defined with enum keyword
  • Use enum keyword to define enumeration, such as enum Color {Red, Green, Blue}
  • When using enumeration, use the enumeration name. xxx to obtain the enumeration value, such as Color.Red
  • The enumeration value is a number type. The enumeration value corresponds to the index of the enumeration description. It is incremented from 0 by default
  • The value of the enumeration can be specified manually and obtained through the enumeration name. xxx
  • You can also obtain the enumeration description in the form of * * enumeration name [enumeration value] * * which is a string type, such as: color [0] = > red
//Define an enumeration first
enum Color {Red, Green, Blue}
//Use enumeration
let c: Color = Color.Green;
console.log(c)// Output 1
//Red, Green and Blue are descriptions. The enumerated value is a number type. In this case, the enumerated value is the index corresponding to the three descriptions. By default, it is incremented from 0. You can manually specify the initial value
//Because the index value corresponding to Green is 1, the result of output c is 1

// Manually specify the first enumeration value, and others will be incremented automatically
enum Color {Red=1, Green, Blue}//Let the enumeration value increment from 1
console.log(Color.Green); //Output 2

//Manually specify all enumeration values
enum Color {Red=1, Green=3, Blue=5}
console.log(Color.Green); //Output 3

//  Get enumeration description based on enumeration value
enum Color {Red, Green, Blue}
console.log(Color[1]);// "Green"
  • Any: any type. Any can be used when the data type of a value is not determined
let a: any;
a = 3;
a = "abc";
a = true
  • Void: no type. It is generally used when a function has no return value. If a variable is defined as void type, it is meaningless because it can only be assigned null or undefined
function helloworl():void{
	console.log('hello world')
}
let a:void = 1;//report errors
let b:void = null;
  • Never represents the type of value that never exists. It is generally used for the return value type of functions that always throw exceptions or never have a return value
function myException(msg: string):never{
	throw new Error(msg)
}

function diedLoop():never{
	while(true){
	}
	return true;
}

Type assertion in TypeScript

Type assertion is similar to a data type conversion. For example, when defining a variable, we do not know what type it is, so we specify an any type. However, in later use, we can obviously determine what type it is according to the value of the variable. At this time, we can use type assertion.
Characteristics of type assertion:

  • Type assertions do not perform data checks because TypeScript will think that we have done the necessary checks
  • Type assertions only take effect at compile time and do not affect the runtime
  • There are two ways to assert a type:
    • In the form of angle brackets: < data type > variable name
    • Through as keyword: variable name as data type
let something: any = "this is a zifuchuan";
let len:number = (<string>something).length;
//perhaps
let len:number = (something as string).length;

summary

In this article, we learned the common data types in TypeScript, summarized the characteristics of each data type and gave the specific code. Finally, I learned a new knowledge: type assertion. I believe that it should not be difficult for small partners with JavaScript foundation to learn. If they are exposed to the backend language, it will be more helpful to learn and understand TypeScript.

All right, little friends, that's all for this sharing. Your favorite little friends are welcome to comment and pay attention!

Posted by PRodgers4284 on Sun, 07 Nov 2021 18:47:34 -0800