“This is the fourth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
Let’s review our Typescript prep and get ready to learn the basics of Typescript.
Basic knowledge of
The type hierarchy in TS
From the above figure, we can see that Top is the complete set and Bottom is the empty set. From the top down, the top type is the parent set of the bottom type.
Underline: values of lower types can be assigned to variables/constants of upper types. Because a variable/constant of type unknown can point to any type of value. So there are no variables of type never (never is an empty set).
Compare Top/Bottom types in different languages
language | Top Type | Bottom Type |
---|---|---|
TypeScript | unknown | never |
PHP | mixed | never |
Python | object | typing.NoReturn |
Kotlin | Any? | Nothing |
Scala | Any? | Nothing |
Java | java.lang.Object | |
C# | System.Object | |
Go | interface{} | |
Perl | Universal | |
C++ | std::any | |
C | void | |
Object Pascal(Delphi) | TObject |
Any
- Any is special because it is both Top Type and Bottom Type.
That is: variables/constants of type any (variables of any other type can be assigned to each other).
However, the any type is insecure and unserviceable, so it should be avoided as much as possible.
- Any is contagious: it makes the places it touches unsafe.
So TS introduced the type-safe unknown Type as the Top Type in 3.0.
- Any hides bugs
Because there is no type information, there is no error if it is used incorrectly.
For example, the string birthDate does not have the getTime() method, but does not report an error.
function calculateAge(birthday: Date){
var ageDate = new Date(Date.now() - birthday.getTime());
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
let birthDate: any = '1999-09-09'
Copy the code
- Any hides code design details: it loses the design of data types.
Since the any type causes so many of these problems, we can either turn strict mode on or disable implicit any in our project’s tsconfig.
unknown
Let a:unknown = 30 //typeof a ==unknown // Unknown type must display annotation TS does not deduce any value as unknown let B1 = a > 123 // Error TS2571:Object is Of type 'unknown' let b2 = a < 123 //Error TS2571 let b3 = a ==123 // typeof B == Boolean // Unknown types can only be compared with let C = a + 10 // Error TS2571 if(typeof a ==='number'){let d = a + 10 //typeof d == number}Copy the code
Highlight: If you cannot predict the type, do not use any, use unknown, narrow the type before using it.
Boolean type (Boolean)
Boolean with only two elements true and false.
Let a = true //typeof a = Boolean var b = false //typeof b = Boolean const c = true //typeof c = true //let var variables will be extended to Let d: Boolean = true //typeof d = Boolean let e: boolean = true //typeof e = boolean //Error TS2322:Type 'false' is not assignable to type 'true' let f :true = false let G: true | false = true / / let g: Boolean / / it is worth noting, true and false of joint type, will be back a Boolean typeCopy the code
The number type
The number type includes: integer, floating point,+_Infinity,NaN.
Let a = 1234 //typeof a = number var b = Infinity * 0.1 //typeof b = number const PI = 3.14 //typeof PI = 3.14 const nan = NaN //typeof NaN = number let c: number = 2.34 //typeof c = number let d: Typeof D = 4.56 //Error TS2322:Type '10' is not assignable to Type '4.56' let e: 4.56 = 10Copy the code
Bigint type
Bigint is a new type that can represent an integer of any size. The number range [-(2^53-1), 2^53-1] bigint literals are numbers followed by a lowercase “n”. Bigint supports adding +, subtracting -, multiplying *, dividing /, remainder %, and power **.
let a = 1234n // typeof a = bigint
const b 5678n // typeof b = 5678n
var c = a + b
const hugeString = BigInt("900789739482") //typeof hugeString = bigint
const hegeHex = BigInt("0*1fffffffffff") // typeof hugeHex = bigint
const rounded = 5n/2n // typeof rounded = bigint rounded = 2n
//Error : Operator '+' cannot be applied to types 'bigint' and '123'
let d = a + 123
let e = a + BigInt(123)
let f = Number(a) + 123
Copy the code
Underline: Bigint cannot be mixed with number.
String type (string)
let a = "hello" // typeof a = string let b = "world" // typeof b = string const c = "!" // typeof c = "!" Type Dir = "north" | "south" | "east" | "west" type Direction = Dir | Capitaliza < Dir > | Uppercase < Dir > / / / / type Direction = Dir | "North" | "South" | "East" | "West" |"NORTH" | "SOUTH" | "EAST" | "WEST" function echoDir(dir: Direction) {consolo.log(dir)} // dir must be Direction echoDir('North') echoDir('north') echoDir('north') echoDir('North') / / the Error type RT = XMLHttpRequestResponseType / / string literal joint / / / / are commonly used to distinguish data type type XMLHttpRequestResponseType = "|" "arraybuffer" | "blob" | "document" | "json" | "text"Copy the code
Symbol type
symbol
The symbol type symbol is a new language feature introduced in ES2015.
import { Equal } form '@type-challenges/unils' let a = Symbol('a') // typeof a = symbol var a1 = Symbol('a') // typeof A1 = symbol //let var Declared variables derived from the symbol type let a2 = unique symbol = a1 //Error //unique symbol must be const const b1x = Symbol('b') //"unique Symbol b1x" // const constant derived from unique Symbol, Typeof b1, typeof b1x> // falseCopy the code
The unique symbol is a group of unique symbols. For example, unique symbol B1 and unique Symbol b1x are two types.
unique symbol
const b2 = b1; // typeof b2 = symbol type R1 = Equal<typeof b2, typeof b1>; // false type R11 = Equal<ypeof b2, symbol>; // true console.log(b1 === b2); // true const b3: typeof b1 = b1; type R2 = Equal<typeof b3, typeof b1>; // true console.log(b1 === b3); // true console.log(Symbol('a') === Symbol('a')); // false // Symbol The first argument is a description, not a Symbol name, not a Symbol ID. Each call to Symbol returns a new Symbol, even if the description is the same console.log(symbol.for ('a') === symbol.for ('a')); // true // symbol. for internally maintains a dictionary that returns a new Symbol if the corresponding Symbol has not been created before, or an already created Symbol if it has.Copy the code
Highlight: Assigning a unique symbol to another const broadens the type to symbol. If you do not want to broaden, you need to display typeof annotations as corresponding constants.
Object Type (Object)
We learn about object types, which can be compared with objects from the following two aspects:
- Define objects and define object types
- Get object keys and get object type key
Array type (Array)
Arrays are annotated in two ways:
- T[]
- Array
Interface generic
Let a = [1, 2, 3] / / typeof a = number [] var b = [' a ', 'b'] / / typeof = b string [] let c = [1. 'a'] / / typeof c = (string | Number) [] const d = (2, 'b'] / / typeof d = (string | number) [] / / const array not narrowed, // Error :Argument of type 'string' is not assignable // to parameter of type 'number' let E = [] // typeof e = any[] // Ts e.push('red') function buildArray(){ let e = []; // typeof e = any [] e.push(1); E.p ush (' red ') / / let e: (string | number) [] / / when leave scope TS can infer the type of array analysis code return e; } const myarray = buildArray() //Error: Argument of type 'boolean' is not // assignable to parameter of type 'string|number' myarray.push(true); myarray.push(2) // ok myarray.push('bule') // okCopy the code
Tuples
A tuple is a subtype of an array, and the element type on each index of a tuple is determined.
Because tuples are created in the same way as arrays, elements must be annotated.
let a : [number] = [1] let b : [string,string,number] = ['a','b',1] b = ['c','d','e'] // Error :Type 'string' is not addignable to type 'number' Let c:[number,number?] [] [/ / support optional operators [1, 2], [3.4, 5.6], [7]] type C = typeof [0] / / the type C = C/number, number? Type StringTuple = [string,...string[]] // Tuples support rest operator // [...string[]] is equivalent to string[], but [string,...string[]] is not equivalent to string[], Let d :StringTuple = ['a','b','c']; type NBS = [number,boolean,...string[]] let list: NBS = [1,false,'a','b','c']Copy the code
Enumeration (Tuple)
The enumeration
Enumeration is essentially a mapping. An object containing the mapping is generated in the value space.
There is bidirectional mapping
- Enumeration values that are not explicitly assigned automatically increment from 0
- Displays enumerations assigned to integers
There is no reverse mapping
- There is no reverse mapping for enumerations of explicitly assigned strings
Enumeration merger
Enumeration merge: Enumerations can be split into segments and merged with namespaces of the same name.
Constant enumeration
Constant enumerations do not create variables in value space and are replaced with the corresponding value wherever references to constant enumerations are made (but this can be controlled with the perserveConstEnum compiler option)
{
"compilerOptions" :{
"preserveConstEnum" : true
}
}
Copy the code
null,undefined,void,never
We can compare JS, TS, specific see null, undefined, void, never:
JS:
- Undefined = {undefiend}, which should indicate that the defiend is Undefined. However, it actually means that the defiend is declared and the value is not assigned
- Null = {Null}, indicating that the declared value is Null or Null
TS:
- Void: Function has no explicit return value
- Type never: the function cannot return
- In JS, void is a unary operator: it executes the following expression value and returns undefined unconditionally.
- Before ES1.3, undefined was not directly accessible! It can only be done by void(0). ES1.3 adds undefined to the Global Object before it can be accessed.
conclusion
Now that we have learned the basics of Typescript, we should have a basic understanding of the ts types before we can move on