What are the basic typescript types

Time:2022-6-15

Tools for compiling TS into JS

npm install -g typescript
Use command: tsc example.ts

Tools that execute TS code but do not compile

1. Nodemon. It will be executed as long as the code is saved. It is recommended

Installation: `` ` NPM intall -g nodemon```
Use: `` ` nodemon example ts ```

2. TS node, execute the TS node command every time

Installation: `` ` NPM install -g TS node```
Use: ``` TS node example ts ```

What are the basic typescript types

Any type, number type, boolean type, array type, tuple type, enum enumeration type, void type, null type, undefine type, never type

/*Any type, any type, indicating that any type value can be assigned*/
Let any:any // equivalent to let any 

/*Number type*/
let num:number = 1;

/*String type*/
let str:string = 'string'

/* boolean */
let boolean:boolean = true;

/*Array type, indicating that the types of elements are the same*/
let arr: number[] = []; //  General writing
let arr1: Array<number> = [1, 2]; //  Use generics to specify that the array contents are of type number
let arr2: Array<string> = ['1', '2']; //  Use generics to specify that the array contents are of string type
let arr3: Array<boolean> = [true, false]; // Use generics to specify that the array contents are Boolean types

/*Tuple type, indicating that the type of the corresponding position of each element should be the same*/
let tuple: [number, string, boolean]; //  Correct writing and one-to-one correspondence of element position types
tuple = [1, 'str', true];
// tuple = [1,2,'str']; //  Misspelling

/*Enum enumeration type used to define a collection of values*/
enum Color { Red, Green, Blue };
let c: Color = Color. Red; //  Take the enumeration value 0 of red in the enumeration type
console. log(c);  //  Output 0
C = 1.1 // in fact, you can assign number type, but you cannot assign other types of values. Color The value of red is number

/*Void type, used to indicate that the function / method has no return value*/
function func():void {
//Return 1 // the returned value is incorrect
Return // it is written correctly. You can leave it blank
}

/*Null type, indicating that it does not belong to any type*/
let nu:null 
Nu = null // correct assignment

/*Undefine type*/
Let und1:any = undefined // this is a general usage. The initialization variable is an undefined value
Let und2: undefined = undefined // correct assignment

/*Never type, indicating that not all the above types can only be exception types*/
let x: never;
let y: number;
// x = 123; //  Running error, numeric type cannot be converted to never type
x = (() => { throw new Error('exception') })(); //  Never type can be assigned to never type
y = (() => { throw new Error('exception') })(); //  Never type can be assigned to numeric type
function error(message: string): never {
throw new Error(message);//  Functions with a return value of never can throw exceptions
}
function loop(): never {
While (true) {} // a function whose return value is never can be an end point that cannot be executed
}

Maybe you want to know why there are no object, array and function types. There are two special objects: regexp and date

In fact, there are all these, because TS retains all the features of JS

Typescript can also be declared as an object type. Except for null type, undefine type and never type, other types can be assigned to it (to understand that everything is an object, hehe)

let obj: Object

obj = function () {}
console.log(typeof obj);//function

obj = {}
console.log(typeof obj);//object

obj = []
console.log(typeof obj);//object

obj = 1
console.log(typeof obj);//number

obj = 'str'
console.log(typeof obj);//string

Obj = undefined // an error is reported
Obj = null // an error is reported

Maybe you still have a lot of doubts about enumeration types. Next, let’s have a deep understanding of enumeration

Enumeration is a way to organize the collection of associated variables. Many programming languages (e.g. C / c\java) have enumerated data types

Enumerations can be divided into numerical enumerations, string enumerations, constant enumerations, open enumerations, and enumerations with static methods

Numeric enumeration

enum Color {
  Red, // 0
  Green, // 1
  Blue // 2
}
console. log(Color.Red);  //  Output 0
console. log(Color.Green);  //  Output 1

The above TS code is compiled into JS code, which is

var Tristate;
(function(Tristate) {
  Tristate[(Tristate['False'] = 0)] = 'False';
  Tristate[(Tristate['True'] = 1)] = 'True';
  Tristate[(Tristate['Unknown'] = 2)] = 'Unknown';
})(Tristate || (Tristate = {}))
console.log(Tristate);
//Tristate output results are as follows
/* {
  '0': 'False',
  '1': 'True',
  '2': 'Unknown',
  False: 0,
  True: 1,
  Unknown: 2
} */
}

You can change the number associated with any enumeration member through a specific assignment. In the following example, we start from 3 and increase it in turn

The increment rule is: if the current position value is not given a specific value, it will be +1 according to the value of the previous position

enum Color {
  Red = 3, 
  Green, 
  Blue 
}
console. log(Color.Red);  //  Output 3
console. log(Color.Green);  //  Output 4

In fact, you can still play like this. You can calculate other values

enum AnimalFlags {
  None        = 0,
  HasClaws    = 1 << 0,
  CanFly      = 1 << 1,
  EatsFish    = 1 << 2,
  Endangered  = 1 << 3,
  //Calculate the above values
  composition  = HasClaws | CanFly | EatsFish | Endangered
}

String Enum

export enum EvidenceTypeEnum {
  UNKNOWN = '',
  PASSPORT_VISA = 'passport_visa',
  PASSPORT = 'passport',
  SIGHTED_STUDENT_CARD = 'sighted_tertiary_edu_id',
  SIGHTED_KEYPASS_CARD = 'sighted_keypass_card',
  SIGHTED_PROOF_OF_AGE_CARD = 'sighted_proof_of_age_card'
}

These can be handled and debugged more easily because they provide meaningful / debuggable strings.

You can use them for simple string comparisons:

// Where `someStringFromBackend` will be '' | 'passport_visa' | 'passport' ... etc.
const value = someStringFromBackend as EvidenceTypeEnum;

// Sample use in code
if (value === EvidenceTypeEnum.PASSPORT) {
  console.log('You provided a passport');
  console.log(value); // `passport`
}

Constant enumeration

Enum types plus const keyword can help improve performance. The following code will be compiled into var lie = 0; Compile here because

No JavaScript will be compiled for enumeration types (in this case, the runtime does notTristateVariable) because it uses inline syntax.

const enum Tristate {
    False,
    True,
    Unknown
}
const lie = Tristate.False;

If there is no const keyword, the compilation result is like this, so the performance is improved

var Tristate;
(function (Tristate) {
    Tristate[Tristate["False"] = 0] = "False";
    Tristate[Tristate["True"] = 1] = "True";
    Tristate[Tristate["Unknown"] = 2] = "Unknown";
})(Tristate || (Tristate = {}));
var lie = Tristate.False;

Constant enumerationpreserveConstEnumsoption

Using inline syntax can significantly improve performance. No at runtimeTristateThe fact of variables is that the compiler helps you not compile into JavaScript some things that are not used at runtime. However, you may want the compiler to still compile enumeration types into JavaScript for searching from string to number or from number to string in the above example. In this scenario, you can use the compile option--preserveConstEnums, which will compilevar TristateSo you can manually use theTristate['False']andTristate[0]。 And this does not affect inlining in any way.

Enumerations with static methods enumerations with static methods

You can useenum + namespaceTo add a static method to an enumerated type. As shown in the following example, we will use static membersisBusinessDayAdd to enumeration:

enum Weekday {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

namespace Weekday {
  export function isBusinessDay(day: Weekday) {
    switch (day) {
      case Weekday.Saturday:
      case Weekday.Sunday:
        return false;
      default:
        return true;
    }
  }
}

const mon = Weekday.Monday;
const sun = Weekday.Sunday;

console.log(Weekday.isBusinessDay(mon)); // true
console.log(Weekday.isBusinessDay(sun));

Open Enum

The following enumerations with the same name can be merged. However, it should be noted that in enums with multiple declarations, only one declaration can omit the initializer of its first enum element, otherwise an error will be reported

enum Color {
  Red,
  Green,
  Blue
}

enum Color {
  DarkRed = 1,
  DarkGreen,
  DarkBlue
}

The results of compiling JS are as follows:

var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 1] = "Green";
    Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
(function (Color) {
    Color[Color["DarkRed"] = 0] = "DarkRed";
    Color[Color["DarkGreen"] = 1] = "DarkGreen";
    Color[Color["DarkBlue"] = 2] = "DarkBlue";
})(Color || (Color = {}));
console.log(Color);
//Output results
/* 
{
  '0': 'DarkRed',
  '1': 'DarkGreen',
  '2': 'DarkBlue',
  Red: 0,
  Green: 1,
  Blue: 2,
  DarkRed: 0,
  DarkGreen: 1,
  DarkBlue: 2
}
*/