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

Examples of TypeScript (25)

TypeScript built-in types.Copy the code

Global object

/ / 1
const fruits: Array<string> = ['banana'.'orange'.'mango'];
Copy the code

Let’s try to check it outArrayWhere is it defined, as shown aboveArrayIt is defined in different files. Different versions or different functions are combined together, as explained earlierinterfaceclassMultiple definitions merge. These files start with libs and end with.d.ts to show that this is a built-in object type.

Built-in objects are objects that exist in the global scope according to standards and are automatically loaded in TypeScript projects.

/ / 2
const date = new Date()
date.getTime()
Copy the code

The date variable becomes the built-in date type, which makes it easy to call the above method.

/ / 3
const reg = /[a-z]/
reg.test('a')
Copy the code

The variable reg is of type RegExp, and the above method can also be called.

Built-in objects

/ / 4
Math.abs(-20)
Copy the code

Unlike other global objects, Math is not a constructor; all of its properties and methods are static.

/ / case 5
let body = document.body
Copy the code

Document is also a built-in object, and the body variable is of type HTMLElement.

Examples of functional types

In addition to built-in types, TypeScript provides several functional types.

Partial Partial makes all incoming types optional.

/ / case 6
interface Person {
    name: string
    age: number
}
type Person2 = Partial<Person>
Copy the code

The Person2 attribute is now optional. Is equivalent to:

interface Person2 { name? : string age? : number }Copy the code

Realization of Partial

type Partial<T> = {
    [k inkeyof T]? :T[k] }Copy the code

Readonly The purpose of Readonly is to mark all properties as Readonly by the type it returns.

/ / case 7
type Person3 = Readonly<Person>
Copy the code

At this point Person3 has become read-only. Is equivalent to:

interface Person3 {
    readonly name: string
    readonly age: number
}
Copy the code

Realize the Readonly:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
Copy the code

Common types of functionality

Partial

: Convert all types to optional Required

: convert all attribute types to mandatory Readony

: convert all attribute types to read-only option Pick

: Select K from T (select small type from large type) Record

: mark K attributes for T type; Exclude

: Exclude

: Exclude

: Exclude

: Exclude

: Exclude

: Exclude

: Exclude

: Therefore, I am, therefore, on the value I pay, therefore I am therefore underpaid. Therefore, I pay on time, therefore I am therefore underpaid. Therefore, I pay on time, therefore I am 6. InstanceType

: get the InstanceType of the constructor type (get the return type of a class)

,>
,>
,>
,>
,>
,>
,>
,>

,>


Finish this! If this article helps you at all, please give it a thumbs up.