TypeScript’s type system performs type checking on data, which avoids unnecessary errors at compile time and is semantically clear to make code easier to read.
TypeScript type checking has three parts:
- Type inference
- Type of protection
- Type compatibility
Never and unknow
The never type represents those that never exist return throw Error() or cannot be specified
The security type of unknown can be assigned to any Unknown only
Second, type inference
Instead of specifying a variable type or the return value type of a function, TypeScript can infer its type based on a few simple rules
1. Base type inference
Initialize variables, set default parameters, and determine return values
2. Best generic type inference
From multiple element type to infer a type, the TypeScript possible to infer a compatible with all types of generic types let x = [1, ‘imooc, null] = > let x: (string | number | null) []
3. Context type inference
Context type inference is left-to-right type inference
class Animal {
public species: string | undefined
public weight: number | undefined
}
const simba: Animal = {
species: 'lion',
speak: true // Error, 'speak' does not exist in type 'Animal'
}
Copy the code
Type assertion
TypeScript extrapolates that types don’t meet your needs. You need to manually specify a type that overwrites its extrapolation, with caution, compile-time syntax, and no run-time implications
1. Keyword AS overrides its type inference
2. First and last tags <>
interface User {
nickname: string;
admin: boolean;
groups: number[]
}
const user = <User>{};
Copy the code
3. Non-empty assertions!
The compiler cannot remove null or undefined, it can use non-null assertions! Manually remove
function fixed(name: string | null):string { return name! .charAt(0) || ''; }Copy the code
Double assertions are rarely used
const user = 'Even' as any an User;
Copy the code
Type compatibility
Determines whether a type can be assigned to another type
1. Structure
TypeScript type compatibility is based on structural types; A structural type uses only its members to describe the type.
2. Compare functions
The compatibility of two functions depends first on the compatibility of arguments and second on the compatibility of return values.
Type compatibility with enumerations
Enum Enum Status {Pending, Resolved, Rejected} let current = status. Pending let num = 0; current = num num = current; Eunm Color {Red, Bulue, Green} let current = status.pending current = color.red // ErrorCopy the code
4. Type compatibility of classes
- When comparing data of two class types, only instance members are compared; static members and constructors are not
- Private and protected members of a class affect compatibility
class Animal { feet! : number; Contructor (name:string, numFeet:number){}} class Size {feet! : number; Contructor (numFeet:number){}} class Dog extends Animal {} Let a:Animal let s:Size let d:Dog ; //ok feet protected feet! : number => Error //s = a; // the parent class can be assigned to the child class because the child class has no members. //ok //d = a; //okCopy the code
5. Type compatibility of stereotypes
If no generic parameters of a generic type are specified, all generic parameters are compared as if they were any. When a generic type is specified, its type compatibility varies depending on whether it is used by a member. Assignment fails when used.
Interface NotEmpty<T> {data: T} let x: NotEmpty<number>; let y: NotEmpty<string>; x = y! // Error // let identity = function<T>(x: T): void {//... } let identity1 = function<T>(y: T): void { // ... } identity = identity1 //okCopy the code
Iv. Type protection
Type protection refers to narrowing the scope of a type, deducing its type by the compiler within a certain block-level scope, and detecting and avoiding illegal operations
Typeof determines the typeof a variable
if(type target === 'string'){
target.tofixed(2) // Error, is not number
target.split('')// true
}
Copy the code
2, instanceof
Typeof determines the underlying type, and instanceof determines whether it is an instanceof an object
3. In determines whether an attribute exists on an object
class User { public nickname: string | undefined public groups: number[]; } function typeGuard(arg: User | Log) { if('nickname' in arg) { arg.nickname = 'imooc'; }}Copy the code
5. Infer keyword declares type variables
In conditional type expressions, you can use the Infer keyword in the extends condition statement to declare a type variable to be inferred
infer
The function of theTypeScript
Extrapolate and store the result of the extrapolate into a type variable,infer
Can only be used forextends
In the statement.
1. ReturnType infer
ReturnType
– Gets the return value type of the function
const add = (x:number, y: number) => x+y; type t = ReturnType<typeof add> // type t = number; Type ReturnType<T extends (... args:any)=> any> = T extends (... args: any) => infer R ? R: any If 'T' satisfies the constraint '(... Args: any) => any ', TypeScript infers the return value of a function and can assign a value to '(... Args: any) => infer R ', and the return type is' R 'by saving it in the type variable' R 'with the keyword' infer '. Otherwise, the return type is' any 'Copy the code
3. With the help of infer implement tuple turn joint type [string, number] – > string | number
type Flatten<T> = T extends Array<infer U> ? U : never;
type T0 = [string, number]
type T1 = Flatten<T0> // string | number;
Copy the code
If the generic parameter T satisfies the constraint Array
, the type variable U is returned.
Interface and type alias type
Both constrain data types.
The difference between:
1. Different types of definitions:
Type alias type can be applied to the original value (string, Boolean, etc.), joint type (string | number), a tuple ([string, number]) cross types (string & number), and any other handwritten type you need.
Interface When declaring an object, function, or class, define the interface first to ensure that the consistency of its data structure is generally an object structure.
2. Different methods of extension or inheritance
Interface implements extends (inheriting ownership) implements (printing must be replicated)
Type is extended by union crossing
3. Whether to create a new type
-
A type alias does not create a new type, but is a reference to an existing type, whereas the interface defines a new type.