1. Know the TypeScript
Programming languages are divided into dynamically typed languages such as JavaScript and statically typed languages such as Java.
Dynamically typed languages have no compilation phase, and JS itself has great flexibility, such as it has no type constraints, a variable may be initialized as a string, but it can also be assigned as a number, which makes us often use JS programming unexpected errors or hidden dangers, resulting in runtime errors.
Statically typed languages, on the other hand, determine the type of each variable at compile time and find most errors. TypeScript is a statically typed language.
TypeScript is extensible JavaScript. Js compatible, with ES6-ES10 syntax support, can be compatible with a variety of browsers, using TS can reduce code errors, can make the program easier to understand and maintain, its code completion, interface tips and other functions can improve our development efficiency.
Here’s a look at some of TypeScript’s basics and common syntax.
2. Install the TypeScript
/ / installation
npm install -g typescript
/ / compile
// If the code has an error, an error will be reported at compile time
// When compiled, a compiled hello.js file is generated
tsc hello.ts
/ / run
node hello.js
Copy the code
3. Common data types
Some common data types are described below
1. The Boolean value
let isDone:boolean = false
// Note that Boolean is the constructor in js,
// Using new Boolean() creates not a Boolean, but a Boolean object
let createdByNewBoolean: Boolean = new Boolean(1);
let createdByNewBoolean: boolean = new Boolean(1);
// Type 'Boolean' is not assignable to type 'boolean'.
// Calling Boolean directly can also return a Boolean type
let createdByBoolean: boolean = Boolean(1);
Copy the code
2. The numerical
let age:number = 10
Copy the code
3. The string
let firstName:string = 'Tom'
Copy the code
4. A null value
Ts uses void to denote functions that do not return any value
function alert() :void{
alert('hhhaaa')}Copy the code
5. A Null, and Undefined
In TS, undefined and NULL are subtypes of all types. That is, a variable of undefined can be assigned to a variable of type number
// This will not cause an error
let num: number = undefined;
Copy the code
6.any
Any indicates any type, can be changed, and can access any property or method without error. The common use of any is to allow arbitrary types of values in an array
If a variable is declared without a type specified, it is recognized as any value type
let notSure:any = 4
notSure = 'may be a string'
let something // Equivalent to let something:any
something = 'seven'
something = 7
Copy the code
An array of 7.
There are two ways to represent an Array. 1 is the type + square bracket, and 2 is the Array generic.
let arr:number[] = [1.2.3] // An array of numeric types is not allowed
let arr2: number[] = [1.'1'.2.3.5];
// Type 'string' is not assignable to type 'number'.
let arr3: number[] = [1.2.3.5];
arr3.push('8');
// Argument of type '"8"' is not assignable to parameter of type 'number'
// Array generics
let arr:Array<numbei> = [1.2.3]
Copy the code
Class arrays: Common class arrays have their own interface definitions, such as IArguments, NodeList, HTMLCollection, etc
function sum() {
let args: IArguments = arguments;
}
Copy the code
8 yuan group
let user:[string.number] = ['Tom'.20] // Specifies the length and type of the array
user[0].slice(1)
user[1].toFixed(2)
user.push('123') // You can only push one of the two types
Copy the code
9. The interface
In ts, an interface is used to define the type of an object, which is used to describe the shape of an object
interface Person { // Interfaces usually start with uppercase letters
name:string;
age:number; address? :string;
/ /? Represents an optional attribute
readonly id:number;
// readonly Indicates that the object is read-only and cannot be reassigned after initialization
[propName:string] :any;
// [propName: string] defines any attribute,
// Once an arbitrary attribute is defined, the type of both the deterministic attribute and the optional attribute must be a subset of its type
}
// The Tom variable should have the same shape as the Person interface
let tom:Person = {
name:'Tom'.age:20.id:898.gender:'male'
}
Copy the code
Function of 10.
1. Function declaration
// Pass the parameter value type x and y and return the value type
function sum(x:number,y:number) :number {
return x+y
}
// Input more or less than the required parameters, is not allowed
// Can you use? Represents an optional parameter that must be followed by a required parameter
function add(x:number,y:number,z? :number) :number{
if(typeof z === 'number') {return x+y+z
}else{
return x+y
}
// Allow default values to be added to parameters
function build(first:string,last:string='hello'){
return first + last
}
let tom = build('Tom')
Copy the code
2. Function expressions
let mySum: (x: number, y: number) = > number = function (x: number, y: number) :number {
return x + y;
};
// ts => is used to indicate the definition of the function. The left is the input type, which needs to be enclosed in parentheses, and the right is the output type.
Copy the code
3. Define function shapes with interfaces
interface ISum {
(x:number.y:number) :number;
}
let add:ISum = function(x:number,y:number){
return x+y
}
Copy the code
11.never
When a function is never completed, such as a throw, you can specify the return value of never to the function
function throwError(message:string,errorCode:number) :never{
throw {
message,
errorcode
}
} // This line will never be executed
throwError('Not Found'.404)
Copy the code
4. Type inference
TypeScript anticipates a type when there is no explicitly specified type. This is type inference.
let name = 'seven' Let name:string = "seven'
name = 7 / / an error
// If no value is assigned at the time of the definition, it will be inferred as any whether or not it is assigned later
let name; // Equivalent to let name:any;
name = 'seven';
name = 7;
Copy the code
5. Union types
Joint type said value can be one of many types, with | separated for each type
let numberOrString:number | string
NumberOrString is allowed to be of type number or String, but not of any other type
numberOrString = 'Seven'
numberOrString = 7
Copy the code
When ts is not sure what type a variable of a union type is, we can only access properties or methods that are common to all types of the union type
function getLength(something: string | number) :number {
return something.length;
// An error is reported because length is not a common property of string and number
}
Copy the code
When a variable of the union type is assigned, a type is inferred according to the rules of type inference:
let numberOrString: string | number;
numberOrString = 'seven'; // Deduce the string type
console.log(numberOrString.length); / / 5
numberOrString = 7; // Deduce the number type
console.log(numberOrString.length); // Compile error
Copy the code
6. Type assertion
When ts is not sure what type a variable of a union type is, it can manually specify the type of a value to access its unique methods and properties, using type assertions with great care to avoid runtime errors.
function getLength(input:string|number) :number{
const str = input as string
if(str.length){
return str.length
}else{
const number = input as number
return number.toString().length
}
}
Copy the code
Built-in objects
There e are many built-in objects in JavaScript that can be directly treated as defined types in TypeScript. The TypeScript core library definition files define all the types needed by the browser environment and are pre-installed in TypeScript
ECMAScript provides built-in objects such as Boolean, Error, Date, and RegExp
let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date(a);let r: RegExp = /[a-z]/;
Copy the code
DOM and BOM provide built-in objects: Document, HTMLElement, Event, NodeList, and so on
let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click'.function(e: MouseEvent) {
// ...
});
Copy the code
8. Type aliases
Give the type a new name, created using type, and used to associate types
type NameOrResolver = string | number;
const a:NameOrResolver = 2
Copy the code
9. Literal string types
Used to restrict the value to one of several strings
type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
// do something
}
handleEvent(document.getElementById('hello'), 'scroll');
Copy the code
Enumeration 10.
Used to restrict the value to a certain range
enum Direction {Up, Left, Down, Right}
console.log(Direction.Up) / / 0
// The enumeration member is assigned a number increasing from 0
console.log(Direction[0]) // Up
// You can also get the enumeration name based on the enumeration value
// You can also manually assign values to enumerators. Unassigned enumerations are incremented by the last one
enum Direction {Up=3, Left=0, Down, Right}
console.log(Direction.Down) / / 1
Copy the code
Class 11.
In addition to implementing all the functionality of ES6 classes, TypeScript adds a few new uses
1. Modifiers and readonly
TypeScript uses three types of access modifiers: public, private, and protected.
- Properties or methods decorated by public are public and can be accessed anywhere. By default, all properties and methods are public
- A privately-decorated property or method is private and cannot be accessed outside the class that declares it
- A protected property or method is protected. It is similar to private, except that it is also allowed to be accessed in a subclass
- When the constructor is decorated as private, the class is not allowed to be inherited or instantiated
- When a constructor is protected, the class is only allowed to be inherited
class Animal {
public name;
private age;
public constructor(name,age) {
this.name = name;
this.age = age; }}let a = new Animal('Jack'.28);
console.log(a.name); // Jack
// The name attribute is set to public, and the name attribute of the instance can be accessed directly
console.log(a.age) / / an error
// Age is set to private and not accessible
Copy the code
Readonly: Read-only attribute keyword. Note that if readonly and other access modifiers exist at the same time, you must write it after them
Modifiers and readonly can also be used in constructor arguments, equivalent to defining and assigning a value to the property in the class, making code more concise.
class Animal {
// public name: string;
public constructor(public name) {
// this.name = name;}}Copy the code
2. Add the ts type to the class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayHi(): string {
return `My name is The ${this.name}`; }}let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
Copy the code
3. Class implementation interface
In general, a class can only inherit from another class. Sometimes different classes may have features in common, which can be extracted as interfaces and implemented using the implements keyword. This feature greatly increases the flexibility of object orientation
interface Alarm {
alert(): void;
}
interface Light {
lightOn(): void;
lightOff(): void;
}
class door {... }class SecurityDoor extends door implements Alarm {
alert() {
console.log('SecurityDoor alert'); }}class Car implements Alarm.Light {
alert() {
console.log('Car alert');
},
lightOn() {
console.log('Car light on');
}
lightOff() {
console.log('Car light off'); }}Copy the code
4. Interface inheritance
interface Alarm {
alert(): void;
}
interface LightableAlarm extends Alarm {
lightOn(): void;
lightOff(): void;
}
//LightableAlarm inherits Alarm,
// In addition to the alert method, there are two new methods lightOn and lightOff
Copy the code
12. The generic
Generics are defined when a function, interface, or class is defined without specifying a specific type in advance, but only when it is used
1. Basic usage
function createArray<T> (length: number, value: T) :Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
// Add
to the function name, where T refers to any input type,
// It can be used in the following input value: T and output Array
createArray<string> (3.'x'); // ['x', 'x', 'x']
// Pass the string value and output an array of string types
createArray<number> (3.2); / / (2, 2, 2]
// Pass in value and output an array of numeric types
// You can define multiple type parameters at once, using the form of tuples
function swap<T.U> (tuple: [T, U]) :U.T] {
return [tuple[1], tuple[0]];
}
swap([7.'seven']); // ['seven', 7]
Copy the code
2. Generic constraints
When we use a generic variable inside a function, we can’t arbitrarily manipulate its properties or methods because we don’t know what type it is. In this case, we can use extends to restrict the function to only those variables that contain a particular property or method. This is a generic constraint
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise> (arg: T) :T {
console.log(arg.length);
return arg;
}
loggingIdentity(7) / / an error
// If loggingIdentity is passed with an arG that does not contain length, an error will be reported at compile time
Copy the code
3. Specify the default types of generic parameters
This default type is used when the type parameter is not specified directly in the code and cannot be inferred from the actual value parameter
function createArray<T=string> (length: number, value: T) :Array<T> {... }Copy the code
4. Generic interfaces
Use interfaces that contain generics to define the shape of the function
interface CreateArrayFunc<T> {
(length: number.value: T): Array<T>;
}
let createArray: CreateArrayFunc<any>;
createArray = function<T> (length: number, value: T) :Array<T> {... } createArray(3.'x'); // ['x', 'x', 'x']
Copy the code
Note that when using a generic interface, you need to define the type of the generic.
Check out the TypeScript tutorial and TypeScript website