This article is a summary of my learning TypeScript programming and TypeScript Introduction Field Notes
An array of
In TypeScript, we can define array types just as in JavaScript, and specify the types of the array elements.
TypeScript definition syntax comes in two forms:
letThe variable name.type> [] = [...].letThe variable name:Array<type> = [...].Copy the code
Example:
/** * The first way to define an array */
// The child elements are arrays of numeric types
let arrayOfNumber: number[] = [1.2.3];
// The child elements are arrays of strings
let arrayOfString: string[] = ['x'.'y'.'z'];
/** * The second way to define an array */
// The child elements are arrays of numeric types
let arrayOfNumber: Array<number> = [1.2.3];
// The child elements are arrays of strings
let arrayOfString: Array<string> = ['x'.'y'.'z'];
Copy the code
Arrays can be defined in either of these ways, and there is essentially no difference, depending on personal habits or team specifications
tuples
A tuple is a subtype of an array. It is a special way to define an array. It has a fixed length and the values at each index bit have a fixed known type. The most important feature of tuples is that they can limit the number and type of elements in an array. They are particularly useful for multivalue returns
There is no concept of tuples in JavaScript. As a dynamically typed language, it has the advantage of naturally supporting arrays of multi-type elements
let fruit:[string.number.boolean] = ["Apple".2.false]
Copy the code
Tuples also support optional and residual elements, as in object types,? Said the optional
-
Optional elements
let trainFars: [number.number? ] [] = [[10.23.5], [2.6.28], [9.42]]Copy the code
The above code indicates that the elements in a two-dimensional array can be one or two elements of the array type
-
The remaining elements
// There is at least one element let friends:[string. string[]] = ["Forest"."Sare"."Tali"."Chloe"] // A list of different types of elements let list:[number.boolean. string[]] = [23.false."a"."b"."c"] Copy the code
Read-only arrays and tuples
Regular arrays are mutable (you can update them with.push,.splice, etc.); But again, we want the array to be immutable, so that when you modify it, you get a new array, and you don’t change the original array. TypeScript natively supports read-only array types for creating immutable arrays. Read-only arrays are not much different from regular arrays, except that you cannot change them in place; To create a read-only array, display the annotation type. To change a read-only array, use non-morphing methods such as.concat(),.slice(), and not variable methods such as.push(),.splice
let args: readonly number[] = [1.2.3.4.5]
let nums: readonly number[] = args.concat(4.5.6)
console.log('args:', args) // args: [ 1, 2, 3, 4, 5 ]
console.log('nums:', nums) // nums: [1, 2, 3, 4, 5, 4, 5, 6]
// Modify the element
args[2] = 10 // The index signature in error type "readonly Number []" can only be read
// Add data
args.push(30) Readonly number[] does not have attribute push
Copy the code
Note that Array types can also use Array; Similar to declaring institutional arrays and tuples, you can also use long-form syntax:
type letter = readonly string[]
type str = ReadonlyArray<string>
type list = Readonly<string[] >// Multitype declaration
type user = readonly [number.string]
type fruit = Readonly<[number.string] >Copy the code
object
The object type represents a type that is not a primitive type, that is, a type that is not number, string, Boolean, BIGint, symbol, NULL, or undefined. However, it is also a useless type, and the following application scenario is used to represent an object.create type.
declare function create(o: object | null) :any;
create({}); // ok
create(() = > null); // ok
create(2); // Compile error
create('string'); // Compile error
Copy the code
Four ways to declare object types in TypeScript
- Object literal representation (for example:
{a: string}
), also called the structure of the object. Use this if you know what fields the object has, or if the values of the object are all of the same type - Empty object literal representation ({}). Try to avoid this
object
Type. Use this if you need an object but have no requirements for the object’s fieldsObject
Type. Use this as much as possible
The enumeration
Enumerations enumerate the values contained in a type. It’s an unordered data structure that maps keys to values; Enumerations can be thought of as compile-time fixed objects, and TypeScript checks for the existence of the specified key when it is accessed
There are two types of enumerations:
- Mapping between strings
- Mapping between strings and numbers
enum Language {
English,
Spanish,
Russian
}
Copy the code
By convention, enumeration names are singular in uppercase; The keys in the enumeration are also uppercase
TypeScript automatically exports numbers for each member of an enumeration, or you can set them manually
The above code can be deduced by TS to obtain the following results:
enum Language {
English = 0,
Spanish = 1,
Russian = 2
}
Copy the code
Values in an enumeration are accessed using a dot or square bracket notation, just like values in an object; If the accessed value is not stored, an error will be reported, but it is usually displayed directly in the editor
let english = Language.English // Point access
let spanish = Language['Spanish'] // Brackets access
Copy the code
The value of the member can also be computed, and it is not necessary to assign a value to all members
enum Language {
English = 100,
Spanish = 200,
Russian // If you do not manually set a fixed value, Russian defaults to 201, which is the number next to the last enumerator
}
Copy the code
Mixed values for enumerations:
enum Colors {
Red = '#c10000',
Blue = '#007ac1',
Pink = 0xc10050.// Hexadecimal literal
White = 255 / / decimal
}
Copy the code
To avoid unsafe access operations, you can specify a safe subset of enumerations using const enum; However, const enums do not allow reverse lookups and behave much like regular JavaScript objects; As follows:
const enum Language {
English,
Spanish,
Russian
}
// Access a valid enumeration key
let english = Language.English / / 0
// Access a nonexistent key
let US = Language.US / / an error
Copy the code
Type inference
In TypeScript, type annotations are declared after the variable (that is, after the type). Unlike in Java and C, the type of a variable is declared first and then the name of the variable
The advantage of using type annotations is that the compiler can deduce the corresponding type from the context of the code, instead of declaring the type of the variable, as shown in the following example:
let x1 = 42; // Infer that the type of x1 is number
let x2: number = x1; // ok
Copy the code
In TypeScript, variables with initialized values, function arguments with default values, and the types returned by functions can all be inferred from the context. For example, we can infer the return type from the return statement, as shown in the following code:
// The return value is also of type number
function add1(a: number, b: number) {
return a + b;
}
const x1= add1(1.1); // Infer that the type of X1 is also number
// Deduce that the type of the argument b is numeric or undefined, and the type of the return value is numeric
function add2(a: number, b = 1) {
return a + b;
}
const x2 = add2(1);
const x3 = add2(1.'1'); / / an Argument of type '" 1 "is not assignable to the parameter of type' number | is undefined
Copy the code
Literal type
In TypeScript, literals can represent not only values but also types, known as literal types
TypeScript supports three literal types:
- A literal string type
- The numeric literal type
- Boolean literal types
let specifiedStr: 'this is string' = 'this is string';
let specifiedNum: 1 = 1;
let specifiedBoolean: true = true;
Copy the code
A literal type is a subtype of a collection type, which is a more concrete expression of a collection type. For example, ‘this is string’ (which represents a string literal) is of type string (or rather a subtype of string), String is not necessarily a ‘this is string’ type, as shown in the following example:
let specifiedStr: 'this is string' = 'this is string';
let str: string = 'any string';
specifiedStr = str; // Error type '"string"' cannot be assigned to type 'this is string'
str = specifiedStr; // ok
Copy the code
A literal string type
In general, we can use a string literal type as the type of a variable, as shown in the following code:
let hello: 'hello' = 'hello';
hello = 'hi'; Type '"hi"' is not assignable to Type '"hello"'
Copy the code
By using the union type of the combination of literal types, we can restrict the parameters of a function to the specified set of literal types. The compiler then checks if the parameters are members of that set.
Therefore, using a literal type (the union type of a combination) can limit the parameters of a function to more specific types than using a string type. This not only improves the readability of the program, but also ensures that the parameter types of the function are guaranteed, thus killing two birds with one stone.
Numeric literal types and Boolean literal types
The use of numeric and Boolean literals is similar to the use of string literals. We can use the union type of a combination of literals to limit the parameters of a function to a more specific type, such as declaring a type like this:
interface Config {
size: 'small' | 'big';
isEnable: true | false;
margin: 0 | 2 | 4;
}
Copy the code
In the above code, we limit the size attribute as a string literal type ‘small’ | ‘big’ isEnable properties for the type of Boolean literals true | false (Boolean literals true and false, only The combination of true | false with direct use of Boolean no difference), margin properties for numeric literals type 0 | 2 | 4.
Type the alias
We can use variable declarations to declare aliases for values and, similarly, for types. Such as:
type Age = number
type Person = {
name: string;
age: Age;
email: string;
}
Copy the code
Age is just a number. TypeScript does not derive type aliases, so you must display annotations:
type Age = number
type Person = {
name: string
age: Age
email: string
}
let age: Age = 22
let forest: Person = {
name: 'Forest',
age,
email: '[email protected]'
}
Copy the code
Wherever the type alias is used, the source type can be replaced without affecting the semantics of the program