Home  >  Article  >  Web Front-end  >  Typescript basic types and comparison with Javascript

Typescript basic types and comparison with Javascript

coldplay.xixi
coldplay.xixiforward
2021-02-12 09:26:283392browse

TypeScript data types and comparison with JavaScript

Typescript basic types and comparison with Javascript

## Free learning recommendations: javascript video tutorial

Article directory

    TypeScript data types and comparison with JavaScript
  • Introduction
  • 1. Data type and basic data type
    • 1. Data type
    • 2. Basic data type
    • 3.Both Relationship
    • 4. Example
  • 2. Literals and variables
    • 1.Literals
    • 2. Variable
    • 3. Example
    • 4. Template literals
  • 3. JavaScript data Type
  • 4. TypeScript data types
  • 5. TypeScript and JavaScript data types comparison
  • Summary

Introduction

This article briefly introduces the data types of TypeScript and the data types of JavaScript. What are the basic data types? How does it relate to data types? Lists a comparison table comparing TypeScript data types and JavaScript data types.


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

1. Data types and basic data types

1. Data type

The data type is actually a data structure built into the programming language. Various programming languages ​​have their own The built-in data structures each have their own characteristics. They are used to build other data structures.

2. Basic data type

Basic type (basic value, basic data type) is a kind of data that is neither an object nor a method (But JavaScript has basic types of wrapped objects, and objects also have methods. For example, the wrapped object Number of the basic data type number is an encapsulated object that allows you to process numeric values). In most cases, basic types directly represent the lowest level language implementation. All primitive types' values ​​are immutable. But what needs to be noted is the difference between the basic type itself and a variable assigned to a basic type. Variables are 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. Example

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

// 使用字符串方法不会改变一个字符串var bar = "bar" //值"bar"是string类型,是js中基础数据类型console.log(bar);// bazbar.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"]

2. Literals and variables

1. Literals

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

2. 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, letters can be uppercase letters from "A" to "Z" and lowercase letters from "a" to "z"

##3. Example

JavaScript literal assignment variable example:

//变量var anyname//var num是变量 = 1是number类型的字面量var num = 1/**
*	javascrip中各种数据类型的字面量赋值
*///1.数组字面量(Array literals)var animal = ["dog","cat","mouse"]//2.布尔字面量 (Boolean literals)var isTrue = truevar 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.14var decimals = -.2345789 // -0.23456789var decimals = -3.12e+12  // -3.12*1012var 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, template literals are also provided. Template strings provide some syntactic sugar to help you construct strings. This is very similar to the string interpolation feature in Perl, Python, Shell, and other languages. In addition, you can add a tag before passing the template string to customize the parsing process of the template string, which can be used to prevent injection attacks, or to establish advanced string-based data abstraction.

The following are examples:

// String interpolation 字符串插值 使用 `xxx ${插值变量}`var name = "World"var str = `Hello ${name}`console.log(str)// Multiline strings`In JavaScript this is
 not legal.`

3. 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, the type will be determined automatically during the execution 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.七种基本数据类型:

    1.Boolean(布尔值):有2个值分别是(true 和 false).
    2.null:一个表明 null 值的特殊关键字。 JavaScript 是大小写敏感的,因此 null 与 Null、NULL或变体完全不同。
    3.undefined:和 null 一样是一个特殊的关键字,undefined 表示变量未赋值时的属性。
    4.Number(数字),整数或浮点数,例如:42 或者3.14159。
    5.BigInt(任意精度的整数) ( 在 ES2020 中新添加的类型),可以安全地存储和操作大整数,甚至可以超过数字的安全整数限制。
    6.String(字符串),字符串是一串表示文本值的字符序列,例如:“Howdy” 。
    7.Symbol(在 ES6/ES2015 中新添加的类型).。一种实例是唯一且不可改变的数据类型。

    2.引用类型:

    1.对象(Object)、数组(Array)、函数(Function),数组,函数是对象的一种

虽然这些数据类型相对来说比较少,但是通过他们你可以在程序中开发有用的功能。对象(Objects)和函数(functions)是这门语言的另外两个基本元素。你可以把对象当作存放值的一个命名容器,然后将函数当作你的程序能够执行的步骤。

四、TypeScript的数据类型

TypeScript几乎支持所有的JavaScript的数据类型,也有特定的数据类型比如枚举,Any,Void,Never等。也就是说TypeScript的数据类型是JavaScript的一个超集。TypeScript通过在JavaScript的基础上添加静态类型定义构建而成。TypeScript通过TypeScript编译器或Babel转译为JavaScript代码,可运行在任何浏览器,任何操作系统。

1.除了JavaScript七种基本数据类型,还有以下:

1.enum(枚举):是对JavaScript标准数据类型的一个补充像C#等其它语言一样,使用枚举类型可以为一组数值赋予友好的名字。默认情况下,从0开始为元素编号。

例子:

//枚举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:有时候,我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容,比如来自用户输入或第三方代码库。 这种情况下,我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用 any类型来标记这些变量。

例子:

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

在对现有代码进行改写的时候,any类型是十分有用的,它允许你在编译时可选择地包含或移除类型检查。 你可能认为 Object有相似的作用,就像它在其它语言中那样。 但是 Object类型的变量只是允许你给它赋任意值 - 但是却不能够在它上面调用任意的方法,即便它真的有这些方法:

例子:

let notSure: any = 4;notSure.ifItExists(); // okay, ifItExists might exist at runtimenotSure.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:某种程度上来说,void类型像是与any类型相反,它表示没有任何类型。 当一个函数没有返回值时,你通常会见到其返回值类型是 void

例子:

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

4.never:never类型表示的是那些永不存在的值的类型。 例如, never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型; 变量也可能是 never类型,当它们被永不为真的类型保护所约束时。
never类型是任何类型的子类型,也可以赋值给任何类型;然而,没有类型是never的子类型或可以赋值给never类型(除了never本身之外)。 即使 any也不可以赋值给never。

例子:

//下面是一些返回never类型的函数:// 返回never的函数必须存在无法达到的终点function error(message: string): never {
    throw new Error(message);}// 推断的返回值类型为neverfunction fail() {
    return error("Something failed");}// 返回never的函数必须存在无法达到的终点function infiniteLoop(): never {
    while (true) {
    }}

5.Tuple:元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。 比如,你可以定义一对值分别为 string和number类型的元组。

例子:

// Declare a tuple typelet x: [string, number];// Initialize itx = ['hello', 10]; // OK// Initialize it incorrectlyx = [10, 'hello']; // Error//当访问一个已知索引的元素,会得到正确的类型:console.log(x[0].substr(1)); // OKconsole.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' 都有 toStringx[6] = true; // Error, 布尔不是(string | number)类型

五、TypeScript与JavaScript数据类型对照比

✅✅ ✅✅✅✅✅✅✅✅✅✅##boolean##number✅ ✅undefined✅✅Object✅❌ ##Array##✅❌ (js is not) ✅ (ts is)❌✅##enum❌❌✅❌✅##never✅SummaryThe above examples introduce the data types of JavaScript and TypeScript, as well as what are the basic data types; briefly introduce variables and literals Quantity, ES6/ES2015 new feature template literal; Finally, there is a comparison table summarizing JavaScript and TypeScript data types.
Data Type JavaScript TypeScript Whether it is a basic type
##null
bigint
string
symbol
tuple(tuple[])
##any
void

Related free learning recommendations:

javascript

(Video)

The above is the detailed content of Typescript basic types and comparison with Javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete