preface

In recent years, the development trend of the front-end has been inseparable from THE TS static type, including my own after using it and never looked back, in the development experience does help us avoid a lot of problems in static compilation, maybe for pure front-end developers to learn TS has a certain cost, But I think if the benefit is greater than the cost then it’s a good idea to give it a shot. So let’s get to the point

introduce

We can in the typescript website provide ts write paradise of case writing, case we speak of the following can be found in the above oneself try (try more, or you will forget after all good, don’t hurt) code entry: www.typescriptlang.org/play?#code/…

The base type

We’ll start with typescript’s base types, which are similar to the types returned by Typeof that we use everyday in JS

number

boolean

string

undefined

null

any

never

void

Probably is the above several types we can see several in JS is also very common, did not see also don’t worry next we will introduce their role and use scenarios

// We create an n and give it the type of number, that is, n can only be assigned the type of number
// This prevents future type errors after the definition because ts automatically generates a warning if it is assigned to another type
let n:number = 1
n = '12' //Error
n = 2 //Ok

let flag:boolean = true
flag = false //Ok
flag = 1 //Error

let s:string = 'Zero lake flush'
s = 'Mad Clean' // Ok
s = 1 //Error

let out:undefined; // The type is undefined

let nu:null = null // The type is null

let an:any = null //any indicates that any type can be set. Avoid using this type in your work

// The never type represents the types of values that never exist
// For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or return no value at all
// When they are bound by type protection that is never true
let nev:never 

// In a way, void is like the opposite of any; it means there is no type
// When a function returns no value, you will usually see the return type void
let vo:void = undefined 
Copy the code

As you can see, if the assignment string prompts you for the number type, this will save us from having some methods fail later in the process because of type assignment errors

The way Typescript defines types

interface

type

Interface

I’m going to talk about interface, and then I’m going to talk about type and the difference between the two, and the following is the definition of interface on the website, which may be a little bit hard to read but it doesn’t matter if we look at a few examples

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.

// Basic operation
//1. Declare the Props interface
interface Props {
    name:string
}
//2. Create the getName function parameter using the Props type
function getName(data:Props){
    let name = data.name
}
//3. Call getName to pass parameters according to the type declared by the interface
getName({name:'Zero lake flush'})

// Inherits the type and can add type parameters
interface userInfo extends Props{
    age:number // Add the age type
}

function getUser(data:userInfo){
    let name = data.name
    let age = data.age
}

getUser({name:'Ren Ying Ying'.age:100})
Copy the code

So this is how the whole interface works and I’m going to give you a little bit of detail inside the function when you’re using data.name if you’re in the editor when you’re done typing data it’s going to tell you what parameters are currently available and when you call getName it’s going to give you a warning if you don’t pass parameters or if you pass a type that doesn’t match the type that you’re currently defining

Ts has some optional operation symbols such as! Non-null assertion operators,? Optional parameter operators,? . Operators,?? The null-value merge operators are introduced in turn

/ /! Non-null assertion operator
// Can be used to assert that operation objects are non-null and non-undefined
// Undefined in this example because of the type of declaration
// So the normal call to cb method will have a warning but add! This then tells the type to ignore undefined and NULL

type fun = () = > void; // Type is described below

function fn(cb: fun | undefined) {
    const num1 = cb(); // Error
    constnum2 = cb! (a);//Ok
}

/ /? Optional parameter operator
// If the interface parameter name is not passed, an error message will be displayed
// But plus? The name can be passed or not passed without prompting

interfaceProps { name? :string
}
function getName(data: Props) {
    let name = data.name
}
getName({name:'Mad Clean'}) // Ok
getName({}) //Ok

/ /? . Operator (already implemented in ECMAScript)
// If null or undefined is encountered during writing, it will automatically stop returning false
// for example 🌰 suppose data is a parameter we get from the interface with value in it and value with name in it
/** {value:{name:' 0 '}} **/
let res = data

// When we want to use name, we might write like this before, writing a lot of tedious verification
let name = res && res.value && res.value.name // Error

// Now you can write it in such a way that if one of the steps does not return normally, it will not cause an exception problem because it cannot be retrieved
letname = res? .value? .name// Ok

/ /?? Null-value merge operator
If the left-hand operand is null or undefined, it returns the right-hand operand; otherwise, it returns the left-hand operand.
// This I think can mainly solve the logic of js 0 or judgment problems, for example 🌰
// You can see that everything is similar to logic except 0

let aa = 0 ?? 'Lin Pingzhi' / / returns 0
let aa = 0 || 'Yue Lingshan' // Return to Yue Lingshan

let aa = null ?? Yue Buqun // return to yue Buqun
let aa = undefined ?? 'Better the Middle' // Return to ning Zhongze
Copy the code

Type

Describe the definition of type, give it a new name, work on primitive values (primitive types), union types, tuples, crossover types, type mappings, and anything else you need to write by hand

// Give the type a new name & apply 🌧 to the original value
type num = number
type n1 = num
let n:n1 = 11 //Ok
let n:n1 = '12' //Error

type str = string

// Declare a union type

type ns = str | num

let ns1:ns = 'Ren Ying Ying' // Ok
let ns2:ns = 1 // Ok 

// The tuple type defines the number of arrays and the array type

type res = [string.number]

let data:res = ['12'.12] //Ok
let data:res = ['12'.false] //number

// Cross type, similar to interface inheritance

interface user {
    name: string;
}
type userInfo = user & {
    age: number;
}

let user: userInfo = { name: 'Invincible in the East'.age: 1 } //Ok

// Type mapping, which is very simple to map all types above A to type B, for example 🌰

type keysList = "name" | "sex"

type copeKey = {
    [key in keysList]: string
}

let res: copeKey = {name: "Invincible in the East".sex: "Female"} //Ok
Copy the code

So let’s summarize the differences between interface and type, and there’s more to it than that and you can try it out for yourself. Interface can be used to describe objects or functions and other basic types. 2. Interface can be inherited, type can not be used, but type can be used to cross types. But type cannot

The generic

In languages like C# and Java, generics can be used to create reusable components that can support multiple types of data. This allows users to use components with their own data types. —- from the official website

So let’s take a look at a couple of examples and see that this is actually a way of describing types

// Generics use the <> symbol to declare that the type passed in is currently required. For example, 🌰

// When called, we pass in the type, which means that the type used in the generic type can be passed in dynamically
function identity<T> (arg: T) :T {
    return arg;
}

identity<string> ('Whatever I do') // Ok
identity<number> (12) // Ok

// We can pass multiple types (isn't that easy)
function identity<T.U.S> (arg: T, name: U, f: S) :T {
    return arg;
}

identity<number.string.boolean> (123.'Zhang Wuji'.false) //Ok
Copy the code

Let’s see how do we define complex type objects

type arrList = Array<any>
let arr:arrList = [] // Ok

// If you need to define the contents of an Array, Array<> is generic
type arrList = Array<string>
let arr:arrList = ['Zen of The Left Cold'] //Ok

// You can also define the contents of an array this way
type arrList = string[]
let arr:arrList = ['Zen of The Left Cold'] //Ok

// The internal type of an array can do this if it is a complex type
type obj = { name: string }
type arrList = obj[]
let arr: arrList = [{ name: '1' }] //Ok

// Or use generics this way
type obj = { name: string }
type arrList = Array<obj>
let arr: arrList = [{ name: '1' }] //Ok

// Specify the value that the variable can receive
type curr = 'age' | 'name'
function getCurr(val:curr){
    return val
}
getCurr('age') //Ok
getCurr('name') //Ok
Copy the code

Advanced typing tools in Typescript

There are several advanced types in TS that support direct type extension and conversion operations

keyof

extends

Partial

Required

Pick

Record

keyof&extends

Keys (); //keyof is an index type query with the same syntax as object.keys (), taking the value of the key as 🌰
interface users {
    age: number.name: string
}
type formtUser = keyof users
function getUser(val: formtUser) {
    return val
}
getUser('name') // Ok
getUser('age') //Ok

We use ts to implement a function that fetches the contents of an object based on the key
There are two problems with this way of writing
//1. The return type cannot be confirmed
//2. Cannot constrain K
const data = {
  age: 101.name: Linghu Chong
}
function getData(o: object, name: string) {
  return o[name]
}
getData(data,'name')

// We can use generics to specify what to input and what to return
//extends represents a conditional type, which can be understood as T inheriting a type from Object
// The other K inherits the key from T.
function getData<T extends Object.K extends keyof T> (o: T, name: K) :T[K] {
  return o[name]
}
getData(data1,'name')

// A separate introduction to the extends condition type, which is similar to the ternary operator in JS, such as 🌰
T extends U ? X : Y
type flag<T> = T extends true ? true : false
type f1 = flag<number> // false
type f2 = flag<false> // false
type f3 = flag<true> // true
Copy the code

Partial&Required

//Partial converts all existing types to optional types
// In daily use we can reuse other defined types without having to redeclare them, for example 🌰

interface school {
    name: string.age: number
}
type formtSchool = Partial<school> // Convert all to optional types here
function getSchool(val: formtSchool) {
}
getSchool({ name: 1 }) //Ok


//Required is the opposite of Partial, which makes all optional types mandatory

type recordSchool = Required<formtSchool>

function getSchool(val: recordSchool) {
}
getSchool({ name: 'Wind green Poplar'.age: 1 }) //Ok

Copy the code

Pick&Record

//Pick can inherit parts of the desired type, such as 🌰
interface User {
    age: number.name: string.sex: string
};
type PickUser = Pick<User, 'age' | 'sex'>
function getUser(val: PickUser) {
}
getUser({ age: 1.sex: 'woman' }) //Ok we only inherit age and sex

//Record is a type mapping, which simply means mapping one type to another type of key
type types = 'a' | 'b'
type data = { name: string.age: number }
type result = Record<types, data> 
Type result = {a: data; b: data; } * /
Copy the code

What if you define the type of a value but don’t know what type it should be?

Just ask TS, for example 🌰

// When we want to define a time type, but do not know what type it should be, we create a time variable ts to tell you
type times = Date
let time:times = new Date(a)//Ok
let time:times = 123 //Error
Copy the code

The end of the

That’s the end of this page, there’s a lot to be said but there’s a lot to be done and the most important thing is to do it in the workplace to feel the benefits of TS

Finally Dragon Boat Festival happiness and health 😄