Typescript
“What will be hot and what to learn in 2022? This article is participating in the” Talk about 2022 Technology Trends “essay campaign.
Why use typescript
The program is easier to understand
- Problem: parameter types of input and output of functions or methods, external conditions, etc
- Dynamic language constraints: procedures such as manual debugging are required
- With Typescript: the code itself answers these questions
Fewer mistakes
- Most errors can be found during compilation
- Eliminate some common mistakes
Very inclusive
- Fully compatible with Javascript
- Third-party libraries can write type files separately
- Most projects support typescipt
A little flaw
- It adds some learning costs
- Increased some development costs in the short term
The data type
Primitive data type
let isDone: boolean = false
let age: number = 10
let firstName: string = 'viking'
let message: string = `Hello, ${firstName}`
let u: undefined = undefined
let n:null = null
let num: number = undefined
Copy the code
Any type
let notSure: any = 4
notSure = 'maybe a string'
notSure = true
notSure.myName
notSure.getName()
Copy the code
Arrays and tuples
An array of
let arr: number[] = [1.2.3]
arr.push(3)
// Arguments class Array IArguments, not Array
function test(){
console.log(arguments);
arguments.length
arguments[0]}Copy the code
tuples
Put elements of different data types together
let user: [string.number] = ['abc'.20]
user.push('1212'You can only push existing typesCopy the code
Interface Interface
interface IPerson{
readonly id: number; // Read-only attribute
name: string
age: numberaddress? :string // Optional attribute
}
let lihua: IPerson = {
id: 1.name: 'lihua'.age: 20
}
Copy the code
function
function add(x: number, y: number, z? :number) :number {
if (typeof z === 'number') {
return x + y + z
} else {
return x + y
}
}
add(1.2)
add(1.2.3)
Copy the code
const add = (x: number.y: number, z? :number) :number= > {
if (typeof z === 'number') {
return x + y + z
} else {
return x + y
}
}
interface ISum{
(x: number.y: number, z? :number) :number
}
let add2: ISum = add
Copy the code
Type inference
The joint type
let numberOrString: number | string
numberOrString.toString() // Common attributes and methods of the union type
Copy the code
Types of assertions
When using non-shared properties and methods, use the AS keyword to treat a variable as a type, or use Typeof to determine the type
// union types
let numberOrString: number | string
function getLength(input: string | number) :number {
const str = input as string
if (str.length) {
return str.length
} else {
const number = input as number
return number.toString().length
}
}
//type guard
function getLength2(input: string | number) :number {
if (typeof input === 'string') {
return input.length
} else {
return input.toString().length
}
}
Copy the code
Enumeration enums
// Enumeration of numbers. Enumerators are assigned incrementing numbers from the first value (default: 0)
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up) / / 0
console.log(Direction[0]) // Up
// String enumeration
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',}const value = 'UP'
if (value === Direction.Up) {
console.log('go up! ')}// Constant enumeration to reduce performance
const enumDirection {... }Copy the code
Generic Generics
Generic basis
Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use.
function echo<T> (arg: T) :T {
return arg
}
const result = echo(true)
function swap<T.U> (tuple: [T, U]) :U.T] {
return [tuple[1], tuple[0]]}const result2 = swap(['string'.123])
Copy the code
Constraints of generic
When you use a generic variable inside a function, you can’t manipulate its properties or methods because you don’t know what type it is beforehand
The extends keyword in Typescript – Technical circle (proginn.com)
interface IWithLength {
length: number
}
function echoWithLength<T extends IWithLength> (arg: T) :T {
console.log(arg.length)
return arg
}
const str = echoWithLength('str') // Have the length attribute
const obj = echoWithLength({ length: 10.width: 10})
const arr2 = echoWithLength([1.2.3])
Copy the code
Used in class
class Queue<T> {
private data = [];
push(item: T) {
return this.data.push(item)
}
pop(): T {
return this.data.shift()
}
}
const queue = new Queue<number>()
queue.push(1)
console.log(queue.pop().toFixed())
Copy the code
Application in interface
interface KeyPair<T, U> {
key: T
value: U
}
let kp1: KeyPair<number.string> = { key: 1.value: "string"}
let kp2: KeyPair<string.number> = { key: 'str'.value: 2 }
let arr: number[] = [1.2.3]
let arrTwo: Array<number> = [1.2.3] // Array has built-in generics
Copy the code
Type aliases and cross types
Type the alias
// type aliase
let sum: (x: number, y: number) = > number
const result = sum(1.2)
type PlusType = (x: number, y: number) = > number
let sum2: PlusType
const result2 = sum2(2.3)
type StrOrNumber = string | number
let result3: StrOrNumber = '123'
result3 = 123
const str: 'name' = 'name'
const number: 1 = 1
type Directions = 'Up' | 'Down' | 'Left' | 'Right'
let toWhere: Directions = 'Left'
Copy the code
Cross type
interface IName {
name: string
}
type IPerson = IName & { age: number }
let person: IPerson = { name: '123'.age: 123 }
Copy the code
Built-in types
//global objects
const a: Array<number> = [1.2.3]
const date = new Date()
date.getTime()
const reg = /abc/
reg.test('abc')
//build-in object
Math.pow(2.2)
//DOM and BOM
let body = document.body
let allLis = document.querySelectorAll('li')
allLis.keys()
document.addEventListener('click'.(e) = > {
e.preventDefault()
})
Copy the code
TypeScript: Documentation – Utility Types (typescriptlang.org)
//Utility Types
interface IPerson {
name: string
age: number
}
let viking: IPerson = { name: 'viking'.age: 20 }
type IPartial = Partial<IPerson> // Optional type
let viking2: IPartial = { name: 'viking' }
type IOmit = Omit<IPerson, 'name'> // Ignore the name type
let viking3: IOmit = { age: 20 }
Copy the code