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

TypeScript common syntax

Type of contract

Use type contraction to resolve errors: Here are some common solutions:

  • Types of assertions
  • Typeguard Typeof in instanceof literal type protection
  • Double assertion

interface

One of TypeScript’s core tenets is type-checking of the structure a value has. It is sometimes called “duck type discrimination” or “structural typing”. In TypeScript, interfaces name these types and define contracts for your code or third-party code.

Interface is a preliminary study

Here’s a simple example to see how the interface works:

function printLabel(labelledObj: { label: string }) {
  console.log(labelledObj.label)
}

let myObj = { size: 10.label: 'Size 10 Object' }
printLabel(myObj)
Copy the code

The type checker looks at calls to printLabel. PrintLabel takes one argument and requires the object argument to have an attribute called label of type string. Note that the object parameters we pass in actually contain many attributes, but the compiler only checks to see if the required attributes exist and if their types match. However, there are times when TypeScript isn’t quite so loose, as we’ll explain a bit below.

Let’s rewrite the above example, this time using an interface: must contain a label attribute of type string:

interface LabelledValue {
  label: string
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label)
}

let myObj = {size: 10.label: 'Size 10 Object'}
printLabel(myObj)
Copy the code

The LabelledValue interface is like a name that describes the structure in the example above. It represents an object that has a label attribute and is of type String. It is important to note that we cannot say that the object passed to printLabel implements this interface as we do in other languages. We’re just going to focus on what the value looks like. As long as the object passed in meets the necessary conditions mentioned above, it is allowed.

It is also worth noting that the type checker does not check the order of attributes, as long as the corresponding attributes exist and the type is correct.

Optional attribute

Not all attributes in the interface are required. Some exist only under certain conditions, or not at all. For example, the parameter object passed to a function has only some attributes assigned.

interface Square {
  color: string,
  area: number } interface SquareConfig { color? : string width? : number }function createSquare (config: SquareConfig) :Square {
  let newSquare = {color: 'white'.area: 100}
  if (config.color) {
    newSquare.color = config.color
  }
  if (config.width) {
    newSquare.area = config.width * config.width
  }
  return newSquare
}

let mySquare = createSquare({color: 'black'})
Copy the code

An interface with optional attributes is similar to a normal interface definition, except that the optional attribute name definition is followed by one. Symbols.

One of the benefits of optional attributes is that you can pre-define possible attributes, and another is that you can catch errors when references to non-existent attributes. For example, if we intentionally misspelled the name of the color attribute in createSquare, we would get an error message:

interface Square {
  color: string,
  area: number } interface SquareConfig { color? : string; width? : number; }function createSquare(config: SquareConfig) :Square {
   let newSquare = {color: 'white'.area: 100}
   if (config.clor) {
     // Error: attribute 'clor' does not exist in type 'SquareConfig'
     newSquare.color = config.clor
   }
   if (config.width) {
     newSquare.area = config.width * config.width
   }
   return newSquare
 }
 
 let mySquare = createSquare({color: 'black'})
Copy the code

Read-only property

Some object properties can only change their value when the object is created. You can specify read-only properties with readonly before the property name:

interface Point {
  readonly x: number
  readonly y: number
}
Copy the code

You can construct a Point by assigning an object literal. After assignment, x and y can never be changed.

let p1: Point = { x: 10.y: 20 }
p1.x = 5 // error!
Copy the code

TypeScript has the ReadonlyArray

type, which is similar to Array

except that all mutable methods are removed, thus ensuring that arrays can never be modified after they are created:

let a: number[] = [1.2.3.4]
let ro: ReadonlyArray<number> = a
ro[0] = 12 // error!
ro.push(5) // error!
ro.length = 100 // error!
a = ro // error!
Copy the code

On the last line of the code above, you can see that it is not possible to assign the entire ReadonlyArray to a normal array. But you can override it with type assertions

a = ro as number[]
Copy the code

Readonly vs const The easiest way to determine whether to use readonly or const is to use it as a variable or as a property. Const as a variable, readonly as an attribute.