This is the 8th day of my participation in Gwen Challenge

Interface and association types

1. Federated type definitions

Joint types represent value can be one of many types, you can through the pipe (|) set the variable types, assignment can be assigned according to the type of set

let money:string | number = 123 
money = '456'
console.log(money);
Copy the code

The results

2. Interface definition

Interface can be understood as a type, a specification, and a constraint, which can constrain arrays, objects, and types. Optional attributes, read-only attributes, and arbitrary attributes can be defined in the interface, which is convenient for debugging during code development. For example:

interface UserSchema{
    name:string,
    age:number
}

let user1:UserSchema = {name:'Joe'.age:1}
Copy the code

If the attributes are missing or the data type is incorrect, the editor will prompt you with an error

  • A doubtful attributes
interface UserSchema2{
    name:string,
    age:number, sex? :string// Indicates doubt. This property is optional
}

let user2:UserSchema2 = {name:'Cathy'.age:18}
console.log(user2);
Copy the code

  • Read-only property
  readonly name:string, // Read-only attribute
Copy the code

  • Union types can also be used in interfaces
 age:number|string, // Union types are used in interfaces
Copy the code
  • [propName:string]: any // Adds attributes dynamically
interface UserSchema2{
   readonly name:string, // Read-only attribute
    age:number|string, // Union types are used in interfacessex? :string// Indicates doubt. This property is optional
    [propName:string]: any // Indicates to dynamically add attributes
}

let user2:UserSchema2 = {name:'Cathy'.age:18.weight:180}

console.log(user2);
Copy the code

  • Defining array constraints
interface IArray{
    [index:number]:number | string
 }
 
 let arr1:IArray = [1.2.'3']
 console.log(arr1);
Copy the code

Arrays and tuples

Definition 1.

An array object is a set of values that are stored in a single variable name. The most common way to define an array object is by type + square brackets, or by array generics

2. The test

  • In the form of array + []
// Define the form of the array type + []
let arr2:(number|string ) [] =[1.2.3.'234']
console.log(arr2);
Copy the code

  • Array + in the form of a generic
// 2. Array generic form
let arrType1:Array<string> =['1'.'234']
let arrType2:Array<number> =[1.2.3.4]
let arrType3:Array<any> =[{name:'zs'.age:'18'}]
console.log(arrType1,'==>arrType1');
console.log(arrType2,'==>arrType2');
console.log(arrType3,'==>arrType3');
Copy the code

3. The tuples

// The type of each element in the array is specified
let originArr: [number,string,boolean] = [1.'2'.true]
console.log(originArr,'===>originArr');
Copy the code