Quick start
The MAC operating system is used, and the package management tool is YARN.
Special note:
- The operations in this article are in
getting start
Directory, pay attention to the execution of their own commands. - The resources
- TypeScript in 5 minutes
- 英 文 : Getting started with TypeScript in 5 minutes
Compile the first one.ts
file
To use typescript, we first install typescript globally via YARN:
yarn global add typescript
Copy the code
This will prompt you to install demo01.ts successfully.
const greeter = (person) = > {
return `Hello, ${person}`;
};
let person = 'wangkaiwd';
document.body.innerHTML = greeter(person);
Copy the code
When we’re done we run the TypeScript compiler on the command line:
tsc demo01.ts
Copy the code
Command not found is displayed because there are some problems with running the YARN Global command on different operating systems. I successfully installed the yarn Global command using the following method:
Yarn Global fails to be executed.
- Yarn global command not working
- global binaries don’t install on mac os sierra
Yarn Global bin yarn config set prefix ~/. Yarn Users who use ZSH need to add the global PATH vim ~/. ZSHRC export PATH="$PATH: 'yarn Global bin`"Copy the code
After executing the above code, save and exit vim mode, and retry:
yarn global add typescript
tsc demo01.ts
Copy the code
The code will execute successfully.
The TSC command, which stands for Type script compiler, is used to compile.ts files into.js files.
For quick learning, we combine nodeJs with typescript. Since there is no DOM and BOM in node, we delete the part about DOM operation in the code and print it directly:
const greeter = (person) = > {
return `Hello, ${person}`;
};
let person = 'wangkaiwd';
console.log(person);
Copy the code
Then the command line executes:
tsc demo01.ts
node demo01.js
Copy the code
As you may have noticed, compiling TypeScript into JavaScript every time and running it from Node can be a bit tedious. Is there any way to run the.ts file directly from Node commands?
After some searching, I found the ts-Node library, which can run TypeScript in Node, greatly facilitating our learning.
Yarn init -y # install the ts-node third-party module yarn add TS-node -dCopy the code
Let’s have fun with this routine
Type annotations
Type annotations in TypeScript are a lightweight way to add constraints to functions or variables
From here, we can experience the advanced features that TypeScript tools bring.
In the example above, we want the greeter to receive a string:
// demo02.ts
const greeter = (person: string) = > {
return `Hello, ${person}`;
};
const person = 'wangkaiwd';
console.log(greeter(person));
Copy the code
Recompile:
npx ts-node demo02.ts
Copy the code
The command line will still successfully output Hello, wangkaiwd.
Now let’s do some bad things to see what TypeScript does:
const greeter = (person: string) = > {
return `Hello, ${person}`;
};
// console.log(greeter()); // expected 1 arguments,but got 0
// console.log(greeter('name1', 'name2')); // expected 1 arguments,but got 2
// const person = null; // Hello, null
// const person = undefined; // Hello, undefined
// const person = 10; // arguments of type 10 is not assignable to parameter of type 'string'
// const person = [1, 2, 3]; // arguments of type 'number[]' is not assignable to parameter of type 'string'
const person = 'wangkaiwd';
console.log(greeter(person));
Copy the code
Through our experiments, we can see some of the strengths of TypeScript:
- You can analyze whether the type of the passed parameter is correct
- You can analyze whether the number of parameters passed in meets the requirements
null
andundefined
It’s a subtype of all types, so we can put it herenull
andundefined
Assigned tostring
Type variable. We can specify this in the configuration file--strictNullChecks
Mark, like thisnull
andundefined
I can only assign tovoid
On their own, this avoids many common problems
However, despite the error message, the code was successfully compiled into JS. You can still use TypeScript even if there are errors in your code, but in those cases, TypeScript warns you that your code may not perform as expected.
interface
In the following example, we use an interface to describe an object with firstName and lastName fields:
interface Person {
firstName: string,
lastName: string
}
const greeter = (person: Person) = > {
return `Hello, ${person.firstName} ${person.lastName}`;
};
const person = { firstName: 'name1', lastName: 'name2' };
console.log(greeter(person));
Copy the code
As you can see, the argument to the function must contain the structure of the interface Person to avoid an error
class
TypeScript supports new JavaScript features. We use class to override this example:
class Student {
fullName: string;
// Public adds the corresponding attribute to the instance:
// Equivalent to the following code:
// firstName: string;
// middleInitial: string;
// lastName: string;
//
// constructor (firstName: string, middleInitial: string, lastName: string) {
// this.firstName = firstName;
// this.middleInitial = middleInitial;
// this.lastName = lastName;
// }
constructor (public firstName: string.public middleInitial: string.public lastName: string) {
this.fullName = `${firstName} ${middleInitial} ${lastName}`; }}interface Person {
firstName: string,
lastName: string
}
const greeter = (person: Person) = > {
return `Hello, ${person.firstName} ${person.lastName}`;
};
const person = new Student('Jane'.'M.'.'User');
console.log(greeter(person)); // hello, Jane User
Copy the code
runTypeScript
Web
application
Finally, let’s look at the effect on the page
Create index. HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./demo05.js"></script>
</body>
</html>
Copy the code
Compile demo05.ts file:
class Student {
fullName: string;
constructor (public firstName, public lastName) {
this.fullName = `${firstName} ${lastName}`; }}interface Person {
firstName: string,
lastName: string
}
const greeter = (person: Person) = > {
return `Hello, ${person.firstName} ${person.lastName}`;
};
const person = new Student('Type'.'Script');
document.body.innerHTML = greeter(person);
Copy the code
tsc demo05.ts
Copy the code
Then open the HTML file in your browser
Now that we’ve seen how to write a simple TypeScript application, let’s dig into the details and apply them.