Indexable type
Typescript has two indexable types: number indexes and string indexes. Number indexes can be used with string indexes, but number indexes must return a subtype of the string index
Index of type number: variables of type number can be arrays and then get data by index
interface App {
[index:number]:string
}
var var1:App=["1"."2"]; console.log(var1[0]); console.log(var1[1]); The result is 1, 2Copy the code
Index of type number: Variables that use index type can be objects whose keys are of type number or string
interface App {
[index:number]:string
}
var var1:App={11:"Return to strin1", 22:"Return to string2"} console.log(var1[11]); console.log(var1[22]); Strin1 String2 interface App {[index:number]:string} var var1:App={"11":"Return to strin1"."22":"Return to string2"} console.log(var1[11]); console.log(var1[22]); Returns strin1 returns string2Copy the code
When a variable uses the number index type, even though it is indexed by number, the number type is actually converted to string and then indexed by string.
That’s why it’s ok to assign a key to a string to a variable of number index.
If the return type of number index type is not a subclass of string index type, compilation will not pass
Animal is not a subclass of ·Dog, so the compiler will report an error.
class Animal { name: string; } class Dog extends Animal { breed: string; } // error: use numeric string index, sometimes get completely different Animal! interface NotOkay { [x: number]: Animal; [x: string]: Dog; }Copy the code
The difference between interface and type
Both interface and type can be used to define Object and function types
interface Point{
x:number;
y:number;
}
interface SetPoint{
(x:number,y:number):void;
}
type Point2 = {
x:number;
y:number;
}
type SetPoint2 = (x:number,y:number) => void;
Copy the code
Interface can only define class,Object, and Function types, but Type can define basic and compound types
type Name = string; type PartialPointX = {x:number; }; type PartialPointY = {y:number; }; type PartialPoint = PartialPointX | PartialPointY; type Data = [number,string,boolean];Copy the code
Interface and type can be inherited
interface extends interface
interface extends type
type extends type
type extends interface
Copy the code
Classes can implements interface and Type, but cannot implement/inherit type of a combined type
Type cannot be redefined, but interfaces can be redefined and automatically merged.
interface Point {x:number; }; interface Point {y:number; }; const point:Pint = {x:1,y:2};Copy the code
# # generics
Generic type can be applied to the function, class, intereface, type, but can not be used for static members of a class.
Examples of generics for function:
function log<T>(value: T): T {
console.log(value);
returnvalue; } // Two callslog<string[]>(['a'.',b'.'c'])
log(['a'.',b'.'c'])
log('Nealyang')
Copy the code
-
T, K extends Keyof T> constrains this is a generic function
-
keyof T
Is to take all constant keys in T (in this example call), i.e. :"name" | "age"
K extends keyof Person
Is the K is"name"
or"age"
function pluck<T, K extends keyof T>(o: T, names: K[]): T[K][] {
return names.map(n => o[n]);
}
interface Person {
name: string;
age: number;
}
let person: Person = {
name: 'Jarid',
age: 35
};
let strings: string[] = pluck(person, ['name'.'name'.'name']); / / /"Jarid"."Jarid"."Jarid"]
console.log(strings)
Copy the code
partial
Partial is used to make an attribute passed in optional. Implementation:
type Partial<T> = { [P inkeyof T]? : T[P] };Copy the code
Required makes the attribute passed in mandatory. The source code is shown below
type Required<T> = { [P inkeyof T]-? : T[P] };Copy the code
Readonly
Change the attribute passed in to a read-only option, source code below
type Readonly<T> = { readonly [P in keyof T]: T[P] };
Copy the code
Record
This type can convert the value of all attributes in K to T type, source code implementation is as follows:
/**
* Construct a type with a set of properties K of type T
*/
type Record<K extends keyof any, T> = {
[P in K]: T;
};
Copy the code
Pick
Take a set of properties of K from T
/**
* From T, pick a set of properties whose keys are in the union K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
Copy the code
Exclude
Exclude Removes a type that belongs to another type.
/**
* Exclude from T those types that are assignable to U
*/
type Exclude<T, U> = T extends U ? never : T;
Copy the code
Extract
Extract (T) Extract (U) from T; Extract (U) from T;
/**
* Extract from T those types that are assignable to U
*/
type Extract<T, U> = T extends U ? T : never;
Copy the code
Omit
A combination of Pick and Exclude to implement the function of ignoring some attributes of the object, source code is as follows:
/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
Copy the code
Types of assertions
Sometimes the compiler does not recognize the type of the variable. In this case, we can assert the variable to a certain type, so that we can use the related properties of the type to fool the compiler.
Note, however, that type assertions are situational. Type assertions occur at compile time, and improper assertions may result in errors at run time.
Recommended type assertions are pre-issued using the AS keyword instead of <> to prevent ambiguity