Typescript basic types and comparison with Javascript

TypeScript data types and comparison with JavaScript



Introduction

This article briefly introduces the data types of TypeScript and the data types of JavaScript. What are the basic data types? The relationship with the data type? Lists the comparison table to compare the data types of TypeScript and the data types of JavaScript.


Tip: The following is the content of this article, the following cases are for reference

One, data type and basic data type

1. Data type

A data type is actually a built-in data structure of a programming language. Various programming languages ​​have their own built-in data structure, each with its own characteristics. They are used to build other data structures.

2. Basic data types

A basic type (basic value, basic data type) is a kind of data that is neither an object nor a method (but JavaScript has a basic type of packaging object, which is an object and also a method. For example, the packaging object Number of the basic data type number is encapsulated. Let you deal with numerical value objects). In most cases, the basic types directly represent the lowest level language implementation. The values ​​of all basic types are immutable. But it should be noted that the difference between the basic type itself and a variable assigned to the basic type. The variable will be assigned a new value, and the original value cannot be changed like arrays, objects, and functions.

3. The relationship between the two

The relationship between them is that the data type is a superset of the basic data type.

4. Examples

The values ​​of JavaScript basic data types are immutable. The following is an example:


// 使用字符串方法不会改变一个字符串
var bar = "bar" //值"bar"是string类型,是js中基础数据类型
console.log(bar);// baz
bar.toUpperCase();
console.log(bar);// baz

//值"bar"本身不会改变,赋值行为可以给变量bar赋予一个新值基本类型的值"BAR",而不是改变它。
bar = bar.toUpperCase();
console.log(bar);// BAR

// 数组也是一种数据类型,但是使用数组方法可以改变一个数组,因此不是基本数据类型
var foo = [];
console.log(foo);               // []
foo.push("plugh");
console.log(foo);               // ["plugh"]

Second, literals and variables

1. Literals

A literal is a constant defined by a grammatical expression; or, a constant defined by a word expression composed of certain words. In JavaScript, you can use various literals. These literals are fixed values ​​given literally in the script, not variables. (Annotation: The literal value is a constant, its value is fixed, and cannot be changed during the running of the program script.)

2. Variable (Variable)

In applications, use variables as symbolic names for values. The name of a variable is also called an identifier, and it needs to follow certain rules. A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be numbers (0-9). Because the JavaScript language is case-sensitive, the letters can be uppercase letters from "A" to "Z" and lowercase letters from "a" to "z"

3. Examples

Examples of JavaScript literal assignment variables:


//变量
var anyname
//var num是变量 = 1是number类型的字面量
var num = 1

/**
*	javascrip中各种数据类型的字面量赋值
*/

//1.数组字面量(Array literals)
var animal = ["dog","cat","mouse"]

//2.布尔字面量 (Boolean literals)
var isTrue = true
var isTrue = false

//3.整数 (Integers)
var num =0 //117 and -345 (十进制, 基数为10)
var num = 015 //0001 and -0o77 (八进制, 基数为8)
var num = 0x1123 //0x00111 and -0xF1A7 (十六进制, 基数为16或"hex")
var num = 0b11 //0b0011 and -0b11 (二进制, 基数为2)

//4.浮点数字面量 (Floating-point literals)
var pi = 3.14
var decimals = -.2345789 // -0.23456789
var decimals = -3.12e+12  // -3.12*1012
var decimals = .1e-23    // 0.1*10-23=10-24=1e-24

//5.对象字面量 (Object literals)
function say(name){
    
    
	console.log("Hello",name)
}
var obj = {
    
    name:"World!",hello:say}
obj.hello(obj.name) // Hello World

//6.字符串字面量 (String literals)
var foo = "foo"
var bar = 'bar'
var multiline = "one line \
				another line "

4. Template literals

In ES2015/ES6, a template literals is also provided, and template strings provide some syntactic sugar to help you construct strings. This is very similar to the features of string interpolation in Perl, Python, Shell, and other languages. In addition, you can add a tag in front of the template string to customize the parsing process of the template string, which can be used to prevent injection attacks, or to build string-based advanced data abstractions.
The following is an example:


// String interpolation 字符串插值 使用 `xxx ${插值变量}`
var name = "World"
var str = `Hello ${
      
      name}`
console.log(str)

// Multiline strings
`In JavaScript this is
 not legal.`
 

Three, JavaScript data types

JavaScript is a weakly typed or dynamic language. This means that you don't need to declare the type of the variable in advance, and the type will be automatically determined during the running of the program. This also means that you can use the same variable to store different types of data: Let's first introduce the data types of JavaScript.

  • The latest ECMAScript standard defines 8 data types:

    1. Seven basic data types:

    1. Boolean (Boolean value): There are two values ​​(true and false).
    2. Null: a special keyword that indicates a null value. JavaScript is case sensitive, so null is completely different from null, NULL, or variants.
    3. Undefined: It is a special keyword like null, undefined represents the property when the variable is not assigned.
    4. Number, integer or floating point number, for example: 42 or 3.14159.
    5. BigInt (arbitrary-precision integer) (new type added in ES2020), can safely store and manipulate large integers, and can even exceed the safe integer limit of numbers.
    6. String (character string), a string is a sequence of characters representing a text value, for example: "Howdy".
    7.Symbol (new type added in ES6/ES2015). An instance is a unique and unchangeable data type.

    2. Reference type:

    1. Object (Object), array (Array), function (Function), array, function is a kind of object

Although these data types are relatively few, but through them you can develop useful functions in the program. Objects and functions are the other two basic elements of this language. You can think of objects as a naming container for storing values, and then think of functions as steps that your program can execute.

Four, TypeScript data types

TypeScript supports almost all JavaScript data types, and there are also specific data types such as enumeration, Any, Void, Never, etc. In other words, the data type of TypeScript is a superset of JavaScript. TypeScript is built by adding static type definitions to JavaScript. TypeScript is translated into JavaScript code by TypeScript compiler or Babel, which can run on any browser and any operating system.

1. In addition to the seven basic data types of JavaScript, there are the following:

1. enum (enumeration ): It is a supplement to JavaScript standard data types. Like other languages ​​such as C#, enumeration types can be used to give friendly names to a group of values. By default, the element number starts from 0.

example:


//枚举
enum Color {
    
    Red, Green, Blue}
let c: Color = Color.Green;
console.log(c) // 1

//你也可以手动的指定成员的数值。 例如,我们将上面的例子改成从 1开始编号:
enum Color {
    
    Red = 1, Green, Blue}
let c: Color = Color.Green;
console.log(c) // 2

//枚举类型提供的一个便利是你可以由枚举的值得到它的名字。 例如,我们知道数值为2,但是不确定它映射到Color里的哪个名字,我们可以查找相应的名字:
enum Color {
    
    Red = 1, Green, Blue}
let colorName: string = Color[2];
console.log(colorName);  // 显示'Green'因为上面代码里它的值是2

2.any : Sometimes, we want to specify a type for variables whose type is not clear at the programming stage. These values ​​may come from dynamic content, such as user input or third-party code libraries. In this case, we don't want the type checker to check these values ​​but directly let them pass the check at the compilation stage. Then we can use the any type to mark these variables.

example:

//any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

The any type is very useful when rewriting existing code. It allows you to optionally include or remove type checking at compile time. You might think that Object has a similar effect, just like it does in other languages. But a variable of type Object only allows you to assign arbitrary values ​​to it-but you cannot call arbitrary methods on it, even if it does have these methods:

example:


let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

//当你只知道一部分数据的类型时,any类型也是有用的。 比如,你有一个数组,它包含了不同的类型的数据::
let list: any[] = [1, true, "free"];
list[1] = 100;值是2

3. Void : To some extent, the void type is like the opposite of the any type, which means that there is no type. When a function does not return a value, you will usually see its return value type is void

example:


function warnUser(): void {
    
    
    console.log("This is my warning message");
}
//声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined和null:
let unusable: void = undefined;

4.never : Never type represents the type of values ​​that never exist. For example, the never type is the return value type of a function expression or an arrow function expression that always throws an exception or does not return a value at all; variables may also be of the never type, when they are never true. When restricted by protection.
The never type is a subtype of any type, and can also be assigned to any type; however, no type is a subtype of never or can be assigned to the never type (except never itself). Even any cannot be assigned to never.

example:


//下面是一些返回never类型的函数:
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    
    
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    
    
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    
    
    while (true) {
    
    
    }
}

5. Tuple : Tuple type allows to represent an array with a known number and type of elements, and the type of each element does not have to be the same. For example, you can define a pair of tuples whose values ​​are string and number.

example:


// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

//当访问一个已知索引的元素,会得到正确的类型:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

//当访问一个越界的元素,会使用联合类型替代:
x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型
console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString
x[6] = true; // Error, 布尔不是(string | number)类型

Five, TypeScript and JavaScript data type comparison

type of data JavaScript TypeScript Basic type
null
bigint
string
symbol
boolean
number
undefined
Object
Array ❌ (js is not) ✅ (ts is)
tuple(tuple[])
enum
any
void
never

to sum up

The above examples introduce the data types of JavaScript and TypeScript, and what are the basic data types; briefly introduce variables and literals, ES6/ES2015 new feature template literals; finally, there is a comparison table summarizing JavaScript and TypeScript data types.

Guess you like

Origin blog.csdn.net/Suarez1987/article/details/113265150