This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
preface
TypeScript, developed by Microsoft, is a superset of JavaScript that extends JavaScript’s syntax.
TypeScript provides compile-time static type checking through type annotations, which can be compiled into JavaScript using TSC commands.
TypeScript is case sensitive.
TypeScript supports two types of comments:
// This is a single-line comment /* this is a multi-line comment */Copy the code
tsc
Install the typescript
npm install -g typescript
Copy the code
You can then use the TSC command to execute TypeScript related code.
tsc
Common commands
See what commands TSC supports:
tsc --help
Copy the code
Common commands are as follows:
-h, --help View the help -v, --version Displays the TSC version number -d, --declaration generates the corresponding '.d.ts' FILE --init initializes the project and generates the tsconfig.json FILE --sourceMap generates the corresponding '.map' FILE --outFile FILE defines the output FILE --outDir DIRECTORY redirects output folders --removeComments removes comments from files -w, -- Watch listens for input files and recompiles if changes occur.Copy the code
Such as:
Tsc-v // Version 4.0.3tsc app. Ts-w //...Copy the code
compileapp.ts
file
The content of app.ts is:
var message:string = "Hello World"
console.log(message)
Copy the code
Compile the file
tsc app.ts
Copy the code
The app.js file is generated with the following contents:
var message = "Hello World";
console.log(message);
Copy the code
Compile multiple TS files simultaneously
tsc file1.ts file2.ts file3.ts
Copy the code
TypeScript compilation process
The TypeScript conversion to JavaScript process is shown below:
ts-node
ts-node is a TypeScript execution engine and REPL for Node.js.
Ts-node is the TypeScript execution engine and node.js REPL(read-evaluate-print-loop, interactive interpreter).
Common commands:
# Execute a script as `node` + `tsc`. ts-node script.ts # Execute code with TypeScript. ts-node -e 'console.log("Hello, world!" )' # Execute, and print, code with TypeScript. ts-node -p -e '"Hello, world!" ' # Pipe scripts to execute with TypeScript. echo 'console.log("Hello, world!" )' | ts-node # Equivalent to ts-node --transpile-only ts-node-transpile-only script.ts # Equivalent to ts-node --cwd-mode ts-node-cwd script.ts # Starts a TypeScript REPL. ts-nodeCopy the code
Examples of REPL
$ ts-node
> let a = "hh"
> a
'hh'
let b:number = "hh"
// error TS2322: Type 'string' is not assignable to type 'number'.
> let c:number = 11
> c
11
Copy the code
The base type
any
You can specify a type for a variable whose type is not yet known.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Copy the code
number
Like JavaScript, all numbers in TypeScript are floating point numbers. These floating point numbers are of type number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
Copy the code
string
let name: string = "Tom";
Copy the code
boolean
let isDone: boolean = false;
Copy the code
An array of
// add [] let arr: number[] = [1, 2]; Let arr: Array<number> = [1, 2]; Example code for defining arrays that store various types of data is as follows: let arrayList: any[] = [1, false, 'fine']; arrayList[1] = 100;Copy the code
tuples
A tuple type is used to represent an array with a known number and type of elements. The types of each element need not be the same.
let x: [string, number]; x = ['hhh', 1]; X = [1, 'HHH ']; / / error console. The log (x [0]); / / output HHHCopy the code
The enumeration
Enumeration types are used to define collections of values.
enum Color {Red, Green, Blue}; let c: Color = Color.Blue; console.log(c); 2 / / outputCopy the code
void
In a way, void is like the opposite of any; it means there is no type at all. When a function returns no value, you usually see the return type void:
function warnUser(): void {
console.log("This is my warning message");
}
Copy the code
null, undefined
Undefined and NULL have their own types called undefined and NULL, respectively. Like void, their own types are not very useful:
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
Copy the code
By default null and undefined are subtypes of all types. This means that you can assign null and undefined to variables of type number.
However, when you specify strictNullChecks, null and undefined can only be assigned to void and their respective checks. This avoids many common problems. Maybe somewhere you want to pass in a string or null or undefined, you can use the combined type string | null | is undefined.
never
Never is a subtype of other types, including null and undefined, and represents a value that never occurs.
/ / enabled - strictNullChecks let x: number | null | undefined; x = 1; X = undefined; // Run correctly x = null; // Run correctlyCopy the code
A variable declared as type never can only be assigned by type never, and in functions it usually behaves as an exception thrown or unable to execute to a termination point (such as an infinite loop), as shown in the following code:
let x: never; let y: number; X = 123; x = 123; X = (()=>{throw new Error('exception')})(); Y = (()=>{throw new Error('exception')})(); Function error(message: string): never {throw new error(message); Function loop(): never {while (true) {}}Copy the code
object
Object represents a non-primitive type, that is, a type other than number, string, Boolean, symbol, NULL, or undefined.
Use the object type to better represent apis like Object.create. Such as:
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
Type Assertion
Type assertions can be used to manually specify the type of a value, that is, to allow variables to change from one type to another.
Type assertions come in two forms. The first is the Angle bracket syntax:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
Copy the code
The other is the as syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
Copy the code
The two forms are equivalent.
When you use JSX in TypeScript, only AS syntax assertions are allowed.
Type Inference
In TypeScript, type inference helps provide types where they are not explicitly specified.
let x = 3;
Copy the code
The type of variable X is inferred to be a number. This inference occurs when initializing variables and members, setting default parameter values, and determining the return value of a function.
If the type cannot be inferred due to a lack of declaration, its type is treated as the default dynamic ANY type.
var num = 2; // Type inferred as number console.log("num variable value "+num); num = "12"; // Error console.log(num);Copy the code