This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

The static types of TS can be artificially divided into two categories:

  • Basic types: Boolean, number, string, Any, Void, Null, Undefined, Never

  • Object types: like arrays, functions, objects, enumerations, tuples.

The base type

The type definition of TS is mainly defined as shown in the following example code:

; (function () {
  /* * In TS, the data type can be defined by the let variable name: data type = variable value value (type annotation) * or it can be defined without specifying the data type, and TS itself will infer the data type */
  / / the Boolean
  let boo: boolean = false // Assigning a non-boolean value throws an exception

  // Number type
  let num: number = 100

  / / string
  let str: string = 'String' // Use single or double quotation marks
  str = 'Template string' // Use the template string definition

  // Any type -> indicates that this type can be a dynamic type, which removes type checking at compile time
  let AnyType: any = 123
  AnyType = true // Repeated assignments do not throw an exception

  // Void type -> usually used for function types that have no return value
  function demo() :void {
    console.log('Test void type')
  }
  demo()

  // There are two special types: null and undefined
  // These two types are subtypes of all types, which means they can be assigned to number, string, etc
  let u: undefined = undefined
  num = u // Assign undefined to a variable of type number
  let n: null = null
  boo = n // Assign a Boolean variable to null}) ()Copy the code

The base type is relatively simple, particularly similar to JavaScript, which simply has one more type definition than JavaScript

TS also has a Never type. This type represents worthy types that will never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all.

Object type

An array of

Arrays in TS are different from arrays in JS. Arrays in TS not only define a variable as an array, but also locate the types in the array.

The sample code looks like this:

; (function () {
  // Define an array type that is just a number
  let arr1: number[] = [1.2.3]
  console.log(arr1)
  // Define an array that can be Boolean values of numeric strings
  let arr2: (number | string | boolean) [] = ['1'.'2'.true]
  console.log(arr2)
  // Define an array of any type
  let arr3 = [1['1'.'2'.true].true]
  console.log(arr3)

  // Define an array of object types. The object must have name and age attributes
  const objectArray: { name: string; age: number }[] = [
    { name: 'Bowl Week'.age: 18},]// Or declare it as a type alias
  // Define a type alias through type
  type User = { name: string; age: number }
  const objectArr: User[] = [{ name: 'Bowl Week'.age: 18 }]
})()

Copy the code

tuples

The tuple type allows you to represent an array with a known number and type of elements that need not be of the same type. The sample code looks like this:

; (function () {
  // Define a tuple of string and number
  let tuple: [string.number] = ['123'.123]
  console.log(tuple) // ['123', 123]
  // Assign by index
  tuple[0] = 'string'
  console.log(tuple) // [ 'string', 123 ]
  // Assign other types
  // tuple[0] = true
  // console.log(tuple) // Throws an exception}) ()Copy the code

The main purpose of a tuple is to constrain each item in an array and its length.

Tuples and arrays can be nested as follows:

// Nesting of tuples and arrays
let tuples: [string.number[[] [] ='123'.123],
    ['456'.456]]Copy the code

In the above code, [string, number] represents a tuple, followed by [], which represents an array of tuples.

object

All of the above types can be contained in one object, as shown in the following example code:

; (function () {
  // Define an object containing two attributes, MyName and age, where MyName is string and age is number
  let obj: {
    MyName: string
    age: number
  }
  // An assignment to an object that throws an exception if it is not assigned to the type specified above
  obj = {
    MyName: 'Bowl Week'.age: 18,}console.log(obj) // {MyName: '1 ', age: 18}}) ()Copy the code

We don’t need to annotate types everywhere in TS, because type inference can help us get their functionality without writing extra code. But if you want to make your code more readable, you can write each type.

Type inference

Sometimes in TypeScript you don’t need to specify a type explicitly, and the compiler will automatically infer the appropriate type, as in this code:

; (function () {
  let myName = 'Bowl Week'
  myName = true // Error: Cannot assign type "Boolean" to type "string"}) ()Copy the code

When we define the myName variable, we do not specify its data type. We just assign it a string value, but if we reassign the value to a non-string value, the compiler will throw an exception.

This is TypeScript’s simplest type inference, where you infer the data type of a variable from the value on the right.

Type inference in type federation

What is type federation see: Federated types, cross types, and type protection

When a variable may have multiple types of values, TypeScript merges the types into a single combined type, as shown in the following example:

let arr = [1.'2'] // Define an array of strings and numbers
// Reassign the array defined above
/ / arr = [true, false] / / errors Cannot assign type "Boolean" type "string | number"

// Here's another example
let val = arr.length === 0 ? 0 : 'Array length is not zero'
/ / val = false / / errors Cannot assign type "Boolean" type "string | number"
Copy the code

Context type

The examples presented up to this point may have inferred the type to the left of = from the value to the right of =. The context type is different from the previous type inference, where the compiler determines the type of a variable based on its current context. Example code is as follows:

; (function () {
  // Define an interface
  interface Person {
    name: string
    age: number
  }
  // Define an array through the interface defined above
  let arr: Person[] = [{ name: 'Bowl Week'.age: 18 }]
  // Iterate over the defined array
  arr.forEach(item= > {
    // Depending on the current environment, the compiler automatically concludes that item is of type Hobby and does not have a Hobby property
    console.log(item.hobby) // No property "hobby" exists on type "Person"
  })
})()


Copy the code

In the above code, we first define an interface for Person, and then use that interface to define an array. When iterating through the array, the compiler concludes that item is of type Person, so the compiler throws an exception.

If we add type annotations to function expression parameters, the context type will be ignored and no errors will be reported. Example code is as follows:

// If type information is specified in the context, the context is ignored.
arr.forEach((item: any) = > {
    // Depending on the current environment, the compiler automatically concludes that item is of type Hobby and does not have a Hobby property
    console.log(item.hobby) // No property "hobby" exists on type "Person"
})

Copy the code

Types of assertions

A type assertion is when you tell TS that the worth data type is something and you don’t need to check it.

This way, it does not affect the runtime, only at compile time. Example code is as follows:

let SomeValue: any = 'this is a string'
/ / a grammar
let StrLength1: number = (<string>SomeValue).length
// Syntax 2 as syntax
let StrLength2: number = (SomeValue as string).length

Copy the code

It is worth noting that only the second syntax is supported when using JSX in TS.

Phase to recommend

  • Summary of 42 front-end layout schemes – Juejin (juejin. Cn)
  • JS advanced must be 5 high order functions – nuggets (juejin. Cn)
  • 6 types of inheritance before ES6 – Digging gold (juejin.cn)
  • – Juejin (juejin. Cn)