The big factory also uses "TypeScript". If you don't roll it up, you have to screw it.

Q: Are there no downsides to good JavaScript?

have! For example, es5's var declaration variable scope problem, and whether the syntax is wrong until the code runs. .

Q: Is JavaScript booming?

right! You can see how many Ess there are. It is undeniable that JavaScript is slowly getting better and better. Whether it is from the underlying design or the application level, the introduction of ES6, 7, 8, etc. will make the language more and more important every time. Modern, safer, and more convenient, but you find that JavaScript is still nowhere near type checking. . Netizens say it's just like the picture

In the blog post, I will use the most simple and easy-to-understand terms to explain the complex points , such as the defined variables. In order to make people understand, they can be changed as you like. I call it aa bb xiaohong, etc. .

Get to know TypeScript 

官网解释:TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. 

      We can understand TypeScript as an enhanced version of JavaScript ES6, ES7, ES8 and other new syntax standards, all of which are
supported, ts will prompt whether to report an error during the compilation stage, if the first assignment variable does not specify a type, it will automatically infer
a lot of types It's not that the company doesn't want to use ts, because many people can't use ts to complete projects, and a lot of people just started using ts as any type
. The unified type in the array is called an array, and the non-uniform type is called a tuple. If you have never touched ts, It doesn't matter if you don't understand, look down, and if you don't understand at the end, please beat me up!

It is recommended to go through the official documentation for 5 minutes to get started with TypeScript · TypeScript Chinese website · TypeScript - a superset of JavaScript 

Download Ts 

  • TypeScript will eventually be compiled into JavaScript to run, so we need to build the corresponding environment:
# 安装命令
npm install typescript -g
# 查看版本
tsc --version

 After writing TypeScript, it can run directly on the browser. After writing TypeScript, it can run directly on the browser, then you need to use ts-node

  • In addition, ts-node needs to depend on two packages, tslib and @types/node:
npm install ts-node -g
npm install tslib @types/node -g

Now, we can run TypeScript code directly through ts-node:

 ts-node xxx.ts

use ts

JavaScript type

define type string

let message: string = 'Hello 活在风浪里。。'
  1.  What's the difference? For ts, the type is strict, and the type is specified before the variable declaration.
  2. ts will prompt whether to report an error during the compilation stage
  3. If you assign a variable for the first time without specifying a type, it will automatically type inference. For example, if you write 10, it is of type number, and now it is of type string, because what you wrote is a string.
  4. Note: The string here is lowercase, which is different from String
    . String is a string type defined in TypeScript, and String is a class defined in ECMAScript.
  5. If we assign a non-string value to message, then an error will be reported

define type number 

At the beginning, I said that it supports es6, es7...ES6 has added binary and octal representation, and TypeScript also supports binary, octal, and hexadecimal representation:

let num1: number = 100 // 十进制
let num2: number = 0b100 // 二级制
let num3: number = 0o100 // 八进制
let num4: number = 0x100 // 十六进制
console.log(num1, num2, num3, num4) // 100 4 64 256

Define type Array 

 The first commonly used

const uname: string[] = [] ;

 There is a conflict in the second react jsx 

const uname: Array<string> = []

define type boolean

let flag: boolean = true

 Define type Symbol

In ES5, if we can't add the same property name to the object, such as the following 

const userinfo = {
  uname: 'holle',
  uname: 'holle' // 报错 不可以在对象里定义相同属性
}

 So you can use the es6 symbol 

const uname= Symbol('uname')
const uname= Symbol('uname')
const info = {
  [uname]: 'tom',
  [uname]: 'tom'// 两个tom是不一样的
}

      Es6 refers to a new primitive data type symbol, which represents a unique value, the seventh language of js, features: the value of symbol is unique, used to solve the problem of variables, the value cannot be operated with other data, create a symbol S needs to be capitalized, and it is different to use the symbol value to pass the value directly. The number created by using the function object symbol.for is the same status code.

It is different to pass two identical values ​​directly and use the symbol number

let s1 = Symbol('Zhang San');

let s2 = Symbol('Zhang San');

console.log(s1====s2); //false is not equal, although they all serve Zhang San, but the memory numbers are different

 Define types null and undefined

const aa: null = null
const bb: undefined = undefined

TypeScripte types (5 types)

define type any

  • In some cases, we really can't determine the type of a variable, and maybe it will change, at this time we can use the any type

// 在不想给某些 变量 添加具体的数据类型时可以用any

let message: any = 'Hello World'
message = 123
message = true
message = {}
console.log(message)

define type unknown

  • unknown is a special type in TypeScript, which is used to describe variables of uncertain type
function str() { 
  return 'abc'
}

function num() {
  return 123
}

// unknow 类型只能复制给 any 和 unknow 类型
// any 类型可以赋值给任意类型 !!

const flag = true
let result: unknown
if (flag) {
  result = str()
} else {
  result = num()
}

console.log(result)

define type void

  • void is usually used to specify that a function has no return value, then its return value is void type:
function sum(num1: number, num2: number): void {
  console.log(num1 + num2)//没有返回值,直接打印
}

sum(20, 30)

 define type never

  •  If a function is an infinite loop or throws an exception, it is not appropriate to write void type or other types as the return value type, we can use the never type. never represents a type whose value will never occur
function bar(): never {
  throw new Error()
}

  define type tuple

  • It is usually recommended to store elements of the same type in an array, and elements of different types are not recommended to be placed in an array. (Can be placed in an object or a tuple) The corresponding value can be obtained according to the index 
const info: [string, number, number] = ['why', 18, 1.88]

const name = info[0]
const age= info[1]

 type of data

 Object types and interfaces can specify the shape of an object

//对象类型

function obj (num: { x: number; y: number }) {
  console.log(num.x)
  console.log(num.y)
}

// num('123') //报错
// num({ x: '123', y: '123' }) // 报错

obj({ x: 123, y: 321 })//类型传入正确

interface 

interface InfoType {
  name: string
  age: number
}
const obj: InfoType = {
  name: 'tom',
  age: 18
}

 optional type 

//对象类型

function obj (num: { x: number; y?: number }) {// y 非必传
  console.log(num.x)
  console.log(num.y)
}


obj({ x: 123, y: 321 })//类型传入正确

obj({ x: 354})// 正确

union type 


function obj ( v : number | string) {

  if (typeof v === 'string') {

     console.log(v) // abc

  } else {

    console.log(v) // 123

  }
}

obj(123)
obj('abc')// 传这两种类型都可以,联合类型就是将多种类型用 管道符 串联

type assertion

  • As I said at the beginning, if the type is not specified by default, the type will be automatically asserted

 

updating. . .

2022 / 3 / 2

Guess you like

Origin blog.csdn.net/m0_57904695/article/details/123139166