Feel typescript definition of variables and data types of magic

Your Javascript capable of reaching the bottleneck? That's because you will not typescript. Master TS, let you develop more accurate and concise.
Today's study, we then start with data types and variables TS, feel their wonderful magic.
A. Variables declaratively
1.1 format variable declaration

We have stressed many times, you need to specify the type identifier in TypeScript define variables.

So complete statement format is as follows:

var / let / const identifiers: data type = assignment;

For example, we declare a message, complete the following wording:

Note: string here is lowercase, and there is a difference String
string is a string type defined TypeScript, String is a class defined in ECMAScript

let message: string = "Hello World";

message = "Hello TypeScript"; // right thing to do
message = 20; // wrong approach, because the message is a string type

1.2. Keyword to declare variables

After TypeScript defined variable (identifier) ​​and ES6 consistency, may be used var, let, const defined:

myname var: String = "abc";
the let myAge: Number The = 20;
const myHeight: Number The = 1.88;
however, we have found that using var keyword a warning:

Feel typescript definition of variables and data types of magic

   var关键字警告

Seen in TypeScript does not propose to use the var keyword, and the main reason for the difference between the upgrade and ES6 and let var is the same, var is no block-level scope, will cause a lot of problems, not started to explore here .

So, after the development, we define and const variable is used primarily let

1.3 Variable type inference

In development, sometimes for convenience, we will not have to write the corresponding data type when you declare each variable, we hope can help us infer the corresponding variable type characteristics TypeScript by itself:

let message = "Hello World";

The above code we did not specify the type, but the message is still virtually a string type:
Feel typescript definition of variables and data types of magicimage02

Assign a number to the message
This is because when a variable is first assignment will be assigned according to the type of content back to infer the type of the variable:

The above message is because the assignment is followed by a string type, so the message although there is no clear explanation, but still is a string type

let message = "Hello World"; // string type
let age = 20; // number type
let isFlag = true; // boolean type

1.4. Statement name error

When we declare a name (many other names also) in TypeScript file, will complain:
Feel typescript definition of variables and data types of magicimage03

Statement name error message
main error message:

Can not reclaim block range variable "name"
in front of us obviously (it's clear that control what I do) did not declare name, but says that we repeat the statement

This is because our typescript will DOM typings as a global operating environment;
so when we declare name, and the DOM attribute global name appeared in the same name;

Feel typescript definition of variables and data types of magicimage04

Statement position name of
how to solve this problem?

There are two options: remove the DOM typings environment and declarations module
Mode 1: Remove DOM typings environment

But this approach is not appropriate for us, because we still hope that in our TypeScript code is compiled DOM
Feel typescript definition of variables and data types of magicimage05

Delete DOM typing

Second way: declare our ts file for a module

Since the emergence of the same name with global variables, then we will be packaged into a script module (module), because the module has its own scope, it will not and the global conflict:

In Typescript, we can use the export ES6 to derive an object, and the file is considered Module
the let name = "coderwhy";

{} Export;
. for 1.5 given the console.log

Furthermore, in order to facilitate the testing we often use console.log to test, but will be reported when using a warning:

console.log warning
this time, we can configure
Feel typescript definition of variables and data types of magicimage06

Configuration tslint
"NO-Console": false

Two. JavaScript data types
2.1. Number type

We have developed digital type is the type often used, TypeScript and JavaScript, like, does not distinguish between integer type (int) and floating point (double), unified number type.

// 1. The basic definition digital type
the let NUM = 100;
NUM = 20;
NUM = 6.66;
if you should know that studied ES6, ES6 new binary and octal representation, but TypeScript also supports binary, octal, sixteen hexadecimal representation:

// 2.其他进制表示
num = 100; // 十进制
num = 0b110; // 二进制
num = 0o555; // 八进制
num = 0xf23; // 十六进制
2.2. boolean类型

boolean类型只有两个取值:true和false,非常简单

// boolean类型的表示
let flag: boolean = true;
flag = false;
flag = 20 > 30;
2.3. string类型

string类型是字符串类型,可以使用单引号或者双引号表示:

注意:如果打开了TSLint,默认情况下推荐使用使用双引号
// string类型表示
let message: string = "Hello World";
message = 'Hello TypeScript';
同时也支持ES6的模板字符串来拼接变量和字符串:

const name = "why";
const age = 18;
const height = 1.88;

const info = my name is ${name}, age is ${age}, height is ${height};
console.log(info);
2.4. array类型

数组类型的定义也非常简单,有两种方式:

但是TSLint会推荐我们使用上面这种方式
const names1: string[] = ["why", "abc", "cba"];
const names2: Array<string> = ["why", "abc", "cba"];
2.5. object类型

object对象类型可以用于描述一个对象:

// object类型表示
const myinfo: object = {
name: "why",
age: 20,
height: 1.88,
};
但是上面的代码会报一个警告:

Feel typescript definition of variables and data types of magicimage07

object定义后警告
这是因为TSLint建议我们所有的key按照字母进行排序,但是这个并不是特别有必要,我们还是可以关闭掉:

Feel typescript definition of variables and data types of magicimage08

关闭TSLint字母排序
"object-literal-sort-keys": false
属性是不可以访问的

如果我们访问myinfo中的属性,会发现报错:

Feel typescript definition of variables and data types of magicimage09

找不到name属性
这是因为TypeScript并不知道某一个object类型上面就有一个name的属性。

但是如果我们让它是类型推断的,就可以正常的访问:

这是因为推导出来的类型,是如下的类型
Feel typescript definition of variables and data types of magicimage10

myinfo的类型
还有一种方法是定义后面会学到的接口,TypeScript一个非常好用的特性就是接口interface,后续我们会进行非常详细的学习

2.6. symbol类型

在ES5中,如果我们是不可以在对象中添加相同的属性名称的,比如下面的做法:

const person = {
identity: "程序员",
identity: "老师",
}
通常我们的做法是定义两个不同的属性名字:比如identity1和identity2。

但是我们也可以通过symbol来定义相同的名称,因为Symbol函数返回的是不同的值:

const s1 = Symbol("identity");
const s2 = Symbol("identity");

const person = {

};
这是Symbol的一个用法,更多其他用法大家可以自行学习,或者等到后续确实需要用到时,我们再详细讲解。

2.7. null和undefined

在 JavaScript 中,undefined 和 null 是两个基本数据类型。

在TypeScript中,它们各自的类型也是undefined和null,也就意味着它们既是实际的值,也是自己的类型:

const n: null = null;
const u: undefined = undefined;
三. TypeScript数据类型
TypeScript在原有的JavaScript基础上引入了很多好用的类型:enum枚举类型、tuple元组类型、any类型、void类型、never类型等”
3.1. enum类型

3.1.1. 枚举的基本定义

枚举类型在很多语言都有的类型,比如C++、Java等等,并且也非常好用,所以TypeScript引入了enum类型,让我们开发更好的方便和安全。

枚举类型通常是定义一组数据:

enum Direction {
EAST,
WEST,
NORTH,
SOUTH,
}

const d1 = Direction.EAST;
const d2 = Direction.NORTH;
3.1.2. 枚举类型的值

枚举类型有自己的值,比如打印上面的d1和d2
Feel typescript definition of variables and data types of magicimage11

打印d1和d2结果
默认情况下,枚举中的数据是从0开始的,我们可以改变它的初始化值,比如下面的代码:

enum Direction {
EAST = 10,
WEST,
NORTH,
SOUTH,
}

const d1 = Direction.EAST;
const d2 = Direction.NORTH;

console.log(d1); // 10
console.log(d2); // 12
也可以全部自己来指定:

enum Direction {
EAST = 10,
WEST = 20,
NORTH = 30,
SOUTH = 40,
}

const d1 = Direction.EAST;
const d2 = Direction.NORTH;

console.log(d1); // 10
console.log(d2); // 30
我们也可以通过对应的值去获取对应的数据名称:

console.log(Direction[10]); // EAST
console.log(Direction[30]); // NORTH
3.2. tuple类型

3.2.1. tuple的基本使用

tuple是元组类型,很多语言中也有这种数据类型,比如Python、Swift等。

const tInfo: [string, number, number] = ["why", 18, 1.88];
const item1 = tInfo[0]; // why, 并且知道类型是string类型
const item2 = tInfo[1]; // 18, 并且知道类型是number类型
3.2.1. tuple和数组类比

初学tuple会觉得它和数组非常相似

但是数组中通常会定义一组相同的数据,如果数据不同会造成类型的丢失:

注意:这里我使用了一种联合类型,后面会讲到
const aInfo: Array<string|number> = ["why", 18, 1.88];
const itema = aInfo[0]; // why,但是并不知道itema是string类型还是number类型
3.3. any类型

在某些情况下,我们确实无法确定一个变量的类型,并且可能它会发生一些变化,这个时候我们可以使用any类型(类似于Dart语言中的dynamic类型)

let a: any = "why";
a = 123;
a = true;

const aArray: any[] = ["why", 18, 1.88];
3.4. void类型

void类型通常用于函数没有返回值时来使用:

首先我们需要说明的是,在TypeScript中函数也是有类型的
下面的函数,虽然我们没有指定它的类型,但是它会通过类型推导出来:

const sum = (num1: number, num2: number) => {
return num1 + num2;
};

// 相当于下面的写法
const sum: (num1: number, num2: number) => number = (num1: number, num2: number) => {
return num1 + num2;
};
Feel typescript definition of variables and data types of magicimage12
sum函数的类型
如果一个函数没有返回值,那么它的返回值类型就是void

我们可以将null和undefined赋值给void类型,也就是函数可以返回null或者undefined
const sayHello: (name: string) => void = (name: string) => {
console.log("hello " + name);
};
3.5. never类型

never类型表示一种从来不会存在的值的类型,有点绕,我们来这样理解:

If a function is an infinite loop, the function will return something? No, then write void type or other type as a return type are inappropriate, we can never use type.
If a function is to throw an exception, this function does not return value is not it? This time we can never use type.
Feel typescript definition of variables and data types of magicimage13
infinite loop function
Feel typescript definition of variables and data types of magicimage14
thrown function
 Note: All content in the public starting number Flutter, TypeScript, React, Node, uniapp, small program development, data structures and algorithms, etc., will also update some of their own learning experience, etc. welcome everyone's attention.
Programming areas still have a long way to go, we must not be satisfied with the current status quo and stagnation. In fact, you stop and think about it, you'll find this one there are many unexplored mysteries await discovery, the road is full of fun. If you're a keen interest in it together and then shine in this area with me.

Guess you like

Origin blog.51cto.com/13007966/2452440