This is the 25th day of my participation in the August Genwen Challenge.More challenges in August
Ts’s past life
- Ts stands for typescript, which is a superset of javascript.
- Ts complements javascript’s weakness as a weakly typed scripting language by adding static type annotations.
- Ts brings some of the features and syntax found in ECMAScript proposals.
- Ts compiles to produce pure JavaScript.
Why use TS?
Many colleagues complained of headache after entering TS.
Var o = {key: ”} ts = {key: ”
When you can use O.key, ts is a red wavy line
In fact, we write our own code, of course, we know all kinds of logic, but the code is actually running environment does not know our logic, and it is our code is to rely on the machine to run
As a result, sometimes we write some bugs that we don’t even know about until we see them when they run
Ts is designed to solve this problem, especially in large projects with many people involved, where a module or requirement requires multiple people to work on it, making it very important that others understand our code.
Understanding code is not about guessing. For example, I have the following function:
function sum(a,b) {return a + b}
Copy the code
This is a summation utility. However, strings can also be added. For example, the result of ‘1’+1 is 11, not 2 as expected. Unfortunately, this error can only be detected during the testing phase, not when you write the code
Change the code to ts:
function sum(a: number, b: number) :number { return a + b}
Copy the code
When you call sum(‘1’, 1), ts will immediately tell you that this is an error and that sum takes two numeric arguments.
Ts installation and use
Ts stands for typeScript. You can visit ts’s Chinese website to learn about typeScript.
Installation:
To use TS, you need to install typeScript, because.ts files don’t run directly in the browser, so when you’re done, you need to use typeScript to compile them into regular.js files.
npm i -g typescript
Copy the code
After installation, you can view the installed version of typeScript
tsc -v
Copy the code
Compiling ts files
Write ts file directly run the following command, you can generate the compiled JS file in the same directory
tsc xxx.ts
Copy the code
Let’s create a new TS file, write the following code, save it, and run the compile
let name: string = 'Tom Hanse'
let isTrue: boolean = true
let number: number = 5
function(color: string){
console.log(color)
}
Copy the code
You can see the compiled JS file generated in the same directory. Open it for comparison
var s = 'Tom Hanse';
var isTrue = true;
var number = 5;
function a(color) {
console.log(color);
}
Copy the code
In fact, there is no obvious difference between the two. The only difference is that ts marks the specific type of each variable. For example, S :string indicates that S is a string value.
The function of this annotation is actually annotation.
Data types in TS
There are also some data types in TS that are consistent with javascript, and of course, ts also extends some data types to complement javascript
Boolean type
let flag: boolean = true
Copy the code
The numerical
let num: number = 1
Copy the code
string
let name: string = 'me, string! '
Copy the code
Null and undefined
let n: null = null
let u: undefined = undefined
Copy the code
The null and undefined types are subtypes of all types, so you can assign either null or undefined to any type
let n: number = 4
n = undefined
let u:undefined
let m = u
Copy the code
A null value
A null value is not the same as null or undefined. A null value is represented by void in ts, which represents a function that does not return any value
function reuturnNothing() :void{
let str: string = 'this function return nothing'
alert(str)
}
Copy the code
Any value
Any is used to represent any type, any properties and methods of any can be accessed without ts reporting an error, and any operation returns a value of any type.
As a result, many people use any casually in their code, turning typescript into Anyscript, which is not desirable or desirable.
let anything: any = 'Tom'
console.log(anything.myname)
console.log(anything.myname())
Copy the code
Note that if a variable is declared without a type and is not assigned a value, it defaults to any type
An array of
There are two ways to define arrays in typescript
let arr: number[] = [1.2.3]
let bookList: Array<string> = ['three body'.Romance of The Three Kingdoms]
Copy the code
Where
is called a generic variable, the usual default is
The generic
Generics can greatly improve code reuse and versatility. The simplest example to understand generics is to return the parameter itself in function A
function a (b: any): any{return b}
Copy the code
This is not ideal, because any is arbitrary, and we want to return the argument itself, but two any types are not necessarily the same type, and if we define them as concrete types, the range of choices is too wide, and this is where generics come in
function a<T>(b:any): T{
return b
}
Copy the code
tuples
A tuple type represents an array with a known number and type of elements. The elements need not be of the same type
let arr: [string.number.boolean]
arr = ['i love you'.3000.true]
Copy the code
If the access element is out of bounds, the union type is used instead, following the code above
arr[3] = 'times'
arr[4] = false
Copy the code
Enum
Enumeration types are used for scenarios that are limited to a certain range of values, such as seven days in a week, red, green, and blue colors
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
Copy the code
Enumerators are assigned numbers increasing from 0, and enumerations are also mapped backwards to enumeration names, which can be used for reverse look-ups:
console.log(Days["Sun"= = =0); // true
console.log(Days[0= = ="Sun"); // true
Copy the code
You can also assign values to enumerations manually
enum Days {Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"= = =7); // true
console.log(Days["Mon"= = =1); // true
console.log(Days["Tue"= = =2); // true
console.log(Days["Sat"= = =6); // true
Copy the code
never
Represents the types of values that never exist, such as function expressions or return value types of arrow function expressions that always throw an exception or have no return value at all
// A function that returns never must have an unreachable end
function error(message: string) :never {
throw new Error(message)
}
// The inferred return value type is never
function fail() {
return error("Something failed")}// A function that returns never must have an unreachable end
function infiniteLoop() :never {
while (true) {}}Copy the code
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