“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Type inference

In TypeScript, type inference helps provide types where they are not explicitly specified.

This inference occurs when initializing variables and members, setting default parameter values, and determining the return value of a function.

Definition without assignment

let a

a = 18
a = 'lin'
Copy the code

If no value is assigned, TS automatically deducts the value to any, and then any value is assigned without error.

Initialize a variable

Such as:

let userName = 'lin'
Copy the code

Since the assignment is a string, TS automatically deduces that userName is a string.

Select * from ‘userName’ where userName = ‘string’;

Set default parameter values

There is also an automatic derivation when the function sets default parameters

For example, define a function that prints the age. The default value is 18

function printAge(num = 18) {
    console.log(num)
    return num
}
Copy the code

The TS will automatically deduce the input type of printAge. If the input type is incorrect, an error will be reported.

Determines the return value of the function

When determining the return value of a function, TS also automatically deduces the return value type.

For example, if a function does not write a return value,

function welcome() {
    console.log('hello')
}
Copy the code

TS automatically deduces that the return value is of type void

In the printAge function, TS automatically deduces that the return value is number.

Let’s see what happens if we make the return value of printAge a string.

function printAge(num = 18) {
    console.log(num)
    return num
}

interface PrintAge {
    (num: number) :string
}

const printAge1: PrintAge = printAge
Copy the code

Int TS (int t, int t, int t, int t, int t, int t)

Best generic type

When you need to infer a type from several expressions, the types of those expressions are used to infer the most appropriate generic type. For instance,

let arr = [0.1.null.'lin'];
Copy the code

Such as:

let pets = [new Dog(), new Cat()]
Copy the code

Although TS can derive the most appropriate type, it is best to define the type at the time of writing.

type arrItem = number | string | null
let arr: arrItem[] = [0.1.null.'lin'];

let pets: Pets[] = [new Dog(), new Cat()]
Copy the code

summary

Type corollaries can help us, but since we’re writing TS, unless we’re using a function that returns void by default, which we all know, it’s best to define the type everywhere.

The issue of

Easily take down TS generics

What is the difference between interface and type in TS?

Easy to understand the basic knowledge of TS summary