Knowledge of TypeScript
What is TypeScript?
-
TypeScript is a superset of JavaScript types. It compiles pure JavaScript and is an open source programming language developed by Microsoft.
-
TypeScript runs in any browser, on any computer, and on any operating system.
-
TypeScript is the cornerstone of developing large-scale applications.
-
TypeScript provides richer syntax hints to check for errors at authoring time.
Differences from JavaScript
TypeScript is statically typed, JavaScript is dynamically typed
- In TypeScript, types are defined. (A type cannot be changed once it has been assigned a value.)
TypeScript data types
To make a program valuable, we need to be able to handle the simplest units of data: numbers, strings, structures, booleans, and so on. TypeScript supports almost the same data types as JavaScript, and it also provides useful enumerated types for us to use.
Basic data types in JavaScript:
Raw data types: String, number, Boolean, NULL, undefined, symbol
Reference data type: Object
Basic TypeScript data types:
In addition to all the basic JavaScript data, several new data types have been added:
- Any (any type),
- Never (
never
Type represents the type of values that never exist. - Void (
void
Type image is associated withany
Type is the opposite and can only be assigned to itundefined
andnull
) - For object type: interface
- Number [], string[], Boolean [], etc.
- Function annotations
Annotations of TypeScript raw data
Notes on Boolean values:
let isDone: boolean = false;
Copy the code
// Note that Boolean cannot be capitalized,
Note: Boolean means the following:
Notes on numbers:
let decLiteral: number = 6;
Copy the code
String annotations:
let myName: string = "bob";
myName = "smith";
let sentence: string = `Hello, my name is ${ myName }.
Copy the code
// Note that this cannot be named by name
Any data type: Any data type;
-
It can be any data type if it’s a different variable
let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean Copy the code
-
In the case of objects, any does not indicate common properties and methods on the stereotype.
let notSure: any = 4; notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) Copy the code
Instead, if it is Object, it prompts you to use an attribute of type Object
let prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'. prettySure.toString() // OK Copy the code
The following figure
-
Variables that do not give an initial value are of type any
let a a = '123' a = 123 Copy the code
void
The void type is like the opposite of any in that it means there is no type. When a function returns no value, you will usually see the return value type void
function warnUser() :void {
console.log("This is my warning message");
// return undefined
}
Copy the code
null & undefined
By default null and undefined are subtypes of all types
When strictNullChecks = false is configured in tsconfig.json, null and undefined are subtypes of all types
let u: number = undefined; // strictNullChecks = false
Copy the code
StrictNullChecks = true is officially recommended, but this flag is turned off in configuration.
Never
The never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all. Variables can also be of type never, when they are bound by type protection that is never true.
(I don’t have much contact with this kind of actual situation at present, and I will learn about it separately when I meet it in the future)
Object
Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.
declare function create(o: object | null) :void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Copy the code
Create (function(){}); create([]);
Type annotation & type inference & union type
When we define a variable, and the variable is raw data, we do not need to type it, and it can deduce what type the variable belongs to.
Figure below: Type inference
So normally, if we could make type inferences, it would be a little tedious to annotate them.
But there must be other cases where we need to do type annotations,
For example, when we define a method, it prompts us to annotate the type
function test(a, b) { // You will be prompted to make type annotations in the editor
return a + b
}
test(1.2)
Copy the code
Make type annotations:
function test(a:number, b:number) {
return a + b
}
test(1.2)
Copy the code
Union type: We can choose one of multiple types
let union: string | number
union= '123' // is OK
union= 123 // is OK
Copy the code
And when we define a function:
function test(a: number | string) {
return a.toString() // Common attributes, OK
// return a.split() // This attribute is unique to String and cannot be used in combination
}
test(1)
Copy the code
So, we have to be careful,
-
Common attributes of union types do not report errors,
But do not use properties unique to one of the union types, such as the split method in String. Number does not have this property, so it will report an error
-
Verify the type when assigning
New interface
Interfaces are used to name these types and define contracts for your code or third-party code.
- Describe the shape of the object;
- An abstraction of part of a class’s behavior;
Simple use :(describe the shape of an object)
// interface cannot have more or fewer attributes by default
interface Person {
name: string
age: number
}
let preson: Person = {
name: 'wpf'.age: 18
}
Copy the code
- Optional attributes: What if there are fewer attributes? Just add it to the property
?
Can. If I want to have multiple attributes, - Any/multi-select attribute
[propName:string]:any
- Read-only properties:
readonly
Add attributes to it
interface Person {
readonly id: number.// Read-only attribute
name: stringage? :number // Optional attribute
[propName:string] :any // Any attribute
}
let preson: Person = {
id: 1.name: 'wpf'.male: 'male'
}
Copy the code
An array of annotation
There are three ways to define arrays:
- Type [] e.g. number[]
- Array generic Array< type > e.g. Array
- Interface mode
Type []
let list: number[] = [1.2.3]; // Default does not write, will be type inference deduce
let list1: (string | number) [] = [1.2.3.'1'] // Union type
Copy the code
Array < type >
let list: Array<number> = [1.2.3];
Copy the code
Interface mode
interface List {
[index: number] :number
}
let list: List = [1.2.3.4.5]
Copy the code
// Union type
interface List {
[index: number] :number | string
}
let list: List = [1.2.3.4.5.'6']
Copy the code
An array of class
// Args is an array of classes