Basic types of data in ts

Posted by Valdoua on Sat, 12 Feb 2022 15:20:28 +0100

ts data type

ts data basic data type

After declaring the type, the type of the variable cannot be changed

A vertical bar |: indicates or is used to connect multiple types (Union types)

question mark? Representative optional

&Represent and

boolean type

let bool:boolean=true

Number type number

let num:number=10

String type string

let str:string="Young people don't know what a rich woman is like. They mistake beauty for treasure"

undefined type

const und:undefined=undefined

null type

const nul:null=null

null and undefined are subtypes of other types and can be assigned to any type

Array type array

let arr:number[]=[1,2,3]

let arr:Array<number>=[10,20,30]

let arr:Array<nunber|string>=["hello",100,200]

After the array is defined, the data type inside must be consistent with that when defining the array, otherwise an error will be reported

Tuple type tuple

let yuanZu:[string,number,boolean,undefined]=['haha',10,true,undefined]

Tuple is a new data type of ts, which can be understood as an array with fixed length and fixed data type at each position

Enum type enum

  enum Color {
    red,
    blue,
    yellow,
  }

  let color = Color.red;
  console.log(color); //0
  console.log(Color[2]); // yellow
  
  enum Sex {
    male = 1,
    female,
  }
  console.log(Sex.male); //1
  console.log(Sex[2]); //female

Each element in the enumeration has a number. By default, it starts from 0 and is incremented by 1; But we can also define it ourselves. eg starts from 1

Enumeration can get the number through the element, or get the corresponding element through the number

Elements can be written directly in Chinese, but we don't recommend it

any type

  let anyType: any = 100;
  anyType = "The moon shines in front of the window, and the window is opened in the rising area; I was slapped in the face and lost all my teeth";
  console.log(anyType);
  let a: any[] = [false, 666, "hello"];

Can be any type, easy to use, but there is no error prompt when compiling; It is equivalent to using js syntax directly

unknown type

Like any, any type of value can be assigned to a variable;

However, if you copy this variable to a variable of a known type, unknow n will report an error, while any will not

  let unknowType: unknown;
  unknowType = 10;
  unknowType = "str";
  console.log(unknowType);
  let c = unknowType;
  let d = 12;
  d = unknowType;  // This line will report an error because d has been inferred to be a number, and unknown cannot be assigned to a number type. If it is any, it will not report an error. Undefined, null and any can be assigned to any type

void type

  function doSomething(): void {
    const str: string = "As long as the rich woman holds it, she moves into the big villa overnight";
  }
  doSomething();
  
  // Assigning a value to void doesn't make much sense
  //   let vo: void = null/undefined;

When a function is declared, void is used after parentheses, which means that the function has no return value (also equivalent to the function returning undefined or null)

Object type object

 interface Person {
    age;
    name;
    height;
  }

  function getFitResult(obj: Person): object | boolean {
    const singleMale = {
      name: "Luca",
      age: 24,
      height: 180,
    };

    if (singleMale.age - obj.age <= 5 && singleMale.height - obj.height < 15) {
      return singleMale;
    } else {
      return false;
    }
  }

  const re = getFitResult({ name: "Ari", age: 24, height: 168 });
  console.log(re);

let a:{name: "Monkey King"}

let a={name: "Monkey King", age?:number}

"Name = [Proca: String]", any type of "name = [Proca: String]:

Union type union

let a:number|string=20
a="hello"

The representation can be one of several types

Tabular form

typeexampledescribe
number0,12,-20Any number
string"hello"Arbitrary string
booleantrue/falseBoolean true/false
Literal ItselfThe value of the limiting variable is the value of the literal value; It's a bit similar to const. You can't change it if you declare it
any*Any type, set to any, is equivalent to turning off TS for this variable, which is similar to js
unknown*Type safe any
voidNull value (undefined)No value (or undefined); Multiple functions have no return value
neverNo valueIt cannot be any value and can be used for function error reporting
object{name:"luca"}Any object; {} is used to specify which attributes are included in the object. After the attribute, say hello, indicating optional
array[1,"fun",true]Arbitrary array
tuple[4,5]Tuple, TS new type, fixed length array
enumenum{A,B}Enumeration, TS new type
undefinedundefinedSubtype of any type
nullnullSubtype of any type

Other related concepts

Type Asserts

Tell the compiler that I know what type it is and what I'm doing

Syntax:

variable as type
<type>variable
  function getLength(str: string | number) {
  Since the received parameter may be an array, the number does not exist length,Direct use will report an error, so use type assertion to solve it
    if ((<string>str).length) {
      // If there is a length, it is a string
      return (str as string).length;
    } else {
      return str.toString().length;
    }
  }

Type inference

If no variable type is specified, he will infer a type according to the assignment

If the value is assigned at the same time as the declaration, TS can automatically detect the variable type; Therefore, if you declare and assign values, you can omit the declaration of types

Only declare, not copy, and the parser will set it to any (implicit any)

let a=100  Inferred as number
let b   //Inferred as any

Topics: Front-end TypeScript ts