TypeScript common data types

Preface

I have always been on the sidelines of TypeScript before, and I always feel that I need to learn it when I work, but the experience of the past few days has indeed taught me a lesson, it is 0202, and the front end is not TypeScript? The hurt is Own, so let's do it!

What is TypeScript

TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript. TypeScript adds optional static typing and class-based object-oriented programming to JavaScript. In fact, TypeScript is equivalent to an enhanced version of JavaScript, but it must be compiled into JavaScript at the end of the run. The biggest purpose of TypeScript is to make programmers more creative and increase productivity. It will greatly enhance the development and debugging of JavaScript writing applications, making JavaScript easy to use for writing large applications and for multi-person collaboration.

Variable type

In order to make the program valuable, we need to be able to handle the simplest data units: numbers, strings, structures, Boolean values, etc. TypeScript supports almost the same data types as JavaScript, and it also provides practical enumeration types for us to use.

Data types in TypeScript

  • Boolean: Boolean
  • Number: numeric type;
  • string: string type;
  • enum: enumerated type
  • any: any type
  • void: empty type
  • Null: null type
  • undefined
  • Never type of value that never exists
  • object object
  • Array: array type
  • Tuple: Primordial type

1. Boolean

Making any business logic judgment requires the participation of the boolean type. The judgment of right and wrong is the most intuitive logical processing. The boolean type has only two values, true and false.

let  isOk:boolean = false
console.log(isOk)//false

2. Number

Like JavaScript, all numbers in TypeScript are floating point numbers. The type of these floating-point numbers is number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports the binary and octal literals introduced in ECMAScript 2015.

let num1:number = 123
let num2:number = 0xf00d
let num3:number = 0b1111
let num4:number = 0o744

console.log(num1,num2,num3,num4)//123 61453 15 484

3 .string

You can use double quotation marks like javascript: ""and single quotation marks:, ''you can also use template strings(``)

let pz:string = "pzeng"
let age: number = 37;
let question: string = `Hello, my name is ${
      
       pz },i love ${
      
      age}`
console.log(question) //Hello, my name is pzeng,i love 37

4. enum

There are many values ​​in this world that are multiple and fixed, such as: the season of the year: spring, summer, autumn, and winter, there are four results. When the result of this kind of variable is a few fixed data, it is the best time for us to use the enumerated type:

//默认情况下,从0开始为元素编号
enum Color {
    
    yello,pink,red} 
let c:Color = Color.pink
console.log(c)//1
//自定义编号
enum Color {
    
    yello=1,pink,red} 
let c:Color = Color.pink
console.log(c)//2
//枚举类型提供的一个便利是你可以由枚举的值得到它的名字
enum Color {
    
    yello=1,pink,red} 
let colorName:string = Color[2]
console.log(colorName)//pink

5.any

Sometimes, we want to specify a type for variables whose types are not known 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. In fact, if the front-end is written too much, sometimes the types are unconsciously unclear. This is a bad habit, and it is also a pain in the front end. For this reason, JavaScript has been criticized many times that it is not suitable for large-scale projects.

var t:any =10
t='你好'
t= false
console.log(t)

6.Void

In a sense, viod is the opposite of any. It means that there is no type. When a function does not return a value, it is usually seen that the type of its return value is void.


function warnUser(): void {
    
    
  console.log("This is my warning message");
}
let unusable: void = undefined;

7.Null 和 Undefined

By default, null and undefined are subtypes of all types. That means you can assign null and undefined to variables of type number.

let u: undefined = undefined;
let n: null = null;

8.never

The 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 constrained by protection.

The never type is a subtype of any type and can be assigned to any type; however, no type is a subtype of never or can be assigned to the never type (except for the never itself). Even any cannot be assigned to never.

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

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

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

9.Object

objectIt represents a non-primitive type, that is, except number, string, boolean, symbol, nullor undefinedtype outside.

Use objecttypes to better express Object.createAPIs like this

declare function create(o: object | null): void;

create({
    
     prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error

10 Array type

//可以在元素类型后面接上 [],表示由此类型元素组成的一个数组
let list1: number[] = [1, 2, 3]
//使用数组泛型,Array<元素类型>
let list2: Array<number> = [1, 2, 3]

11 Tuple

The 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.

let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error
console.log(x[0].substr(1)); // ello
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

Guess you like

Origin blog.csdn.net/pz1021/article/details/105827323