1. Why use TypeScript
TypeScript
can allow us to avoid some type or
some code results that are not what we expected. xxx is not defined We all know that the
JavaScript
error is thrown during operation, but the TypeScript
error is directly notified to us in the editor, which greatly improves the development efficiency and does not take a lot of time to write a single test At the same time, it also avoids a lot of time to investigate Bug
.
Second, the advantages and disadvantages of TypeScript
advantage
- Generally, when we are in front-end and back-end joint debugging, we have to look at the field type on the interface document, and
TypeScript
will automatically help us identify the current type. It saves us time to look at thedocument or
network
. This is called type inference (we will talk about it later) - Prompt errors in the editor friendly to avoid the pitfalls of implicit type conversion of the code at runtime.
shortcoming
- There are some learning costs,
TypeScript
There are several types of concepts,interface interfaces,
class category,
enum enumeration,
generics generics such as these we need to spend time learning.
- It may not be perfect in combination with some plug-in libraries
Three, TypeScript running process and JavaScript code running process
1. The JavaScript running process is as follows, which depends on the NodeJs environment and the browser environment
- Convert
JavaScript
code toJavaScript-AST
- Convert
AST
code to bytecode - Calculate bytecode during operation
2. TypeScript running process. The following operations are all TSC operations. After the three steps are executed, continue with the above operations, let the browser parse
TypeScript
code toTypeScript-AST
- Check type check on
AST
- After type checking, it compiles to
JavaScript
code JavaScript
code is converted toJavaScript-AST
- Convert
AST
code to bytecode - Calculate bytecode during operation
Fourth, the difference between TypeScript and JavaScript
Only when we understand the difference between the two can we better understand TypeScript
Type system characteristics | JavaScript | TypeScript |
---|---|---|
How are types bound? | dynamic | Static |
Is there type implicit conversion? | Yes | no |
When to check the type? | Runtime | Compile time |
When to report an error | Runtime | Compile time |
Type binding
JavaScript
JavaScript
dynamically binds the type, only the running program can know the type, and JavaScript
knows nothing about the type before the program runs
TypeScript
TypeScript
will know the current type before the program runs (that is, when it is compiled). Of course, if the variable does not have a defined type, then TypeScript
will automatically be derived from the type.
Type conversion
JavaScript
For example, in JavaScript
the 1 + true
Such a snippet, JavaScript
implicit conversion exists, then true
becomes number
type number(true)
and adding 1.
TypeScript
In TypeScript
in 1+true
such code will TypeScript
error, suggesting number
type can not boolean
types operation.
When to check the type
JavaScript
In JavaScript
, the type can only be checked when the program is running. There will also be implicit conversions of types, which is a pitfall.
TypeScript
In TypeScript
, the type will be checked at compile time. If it does not match the expected type, an error will be reported in the editor and will become popular
When to report an error
JavaScript
In JavaScript
only when the program is executed to throw an exception, JavaScript
when there is an implicit conversion, program execution so we can truly know the code type is the expected type, the code is not valid.
TypeScript
In TypeScript, when you write code in the editor, if there is an error, an exception will be thrown directly, which greatly improves efficiency and is convenient.
Five, TypeScript revolves around two modes in total
Explicit annotation type
Give a chestnut
let name: string = "前端娱乐圈";
let age: number = 38;
let hobby: string[] = ["write code", "玩游戏"]
The explicit annotation type is to define the type when declaring the variable (the official discourse is with the annotation when declaring), let us understand at a glance, oh~, this name
is a string
type.
Derivation type
Give a chestnut
let name = "前端娱乐圈"; // 是一个string类型
let age = 38; // 是一个number类型
let hobby = ["write code", "玩游戏"] // 是一个string数组类型
To derive the type is to remove the display annotations, and the system will automatically recognize what type the current value is.
6. Install TypeScript && Run
typescript
Install the typescript
environment globally.
npm i -g typescript
But this is only the installation of typescript
, so how do we run the .ts
file? After installing typescript
we can execute the tsc
command.
For example, our file is called index.ts
tsc index.ts
directly on the command line. Then you can see a index.js
compiled in the directory, which is the result of tsc
index.ts
const userName: string = "前端娱乐圈"
Run tsc index.ts
, you can see in index.ts
turn generates a sibling under index.js
, the following is a compilation of the results file index.js
.
var userName = "前端娱乐圈"
Above we know that running the tsc
command can compile and generate a file. Some friends find it too troublesome. Every time you run, you just compile a file and not run it. You have to use node index.js
to run it. No hurry, let's look down
ts-node
Let's take a look at this plug-in ts-node
, this plug-in can directly run the .ts
file, and will not compile the .js
file.
npm i ts-node
// 运行 ts-node index.ts
Speaking of this, we understand uses TypeScript and its advantages and disadvantages and its operation mode .
Then step into the TypeScript
basic knowledge of 0612c73ed1e8bc~, follow me.
feel helpful can pay attention to: 1612c73ed1e8ce front-end entertainment circle public account, thank you~, update a little trick every day
Seven, basic knowledge
1. Basic static typing
In TypeScript
the basis of the type with us JavScript
the base type is the same. There are only new Ts
1. number
const count: number = 18; // 显示注解一个number类型
const count1 = 18; // 不显示注解,ts会自动推导出来类型
2. string
const str: string = "前端娱乐圈"; // 显示注解一个string类型
const str1 = "蛙人"; // 不显示注解,ts会自动推导出来类型
3. boolean
const status: string = false; // 显示注解一个string类型
const status1 = true; // 不显示注解,ts会自动推导出来类型
4. null
const value: null = null;
const value: null = undefined; // 这一点null类型可以赋值undefined跟在 js中是一样的,null == undefined
5. undefined
const value: undefined = undefined;
const value: undefined = null; // 这一点null类型可以赋值undefined跟在 js中是一样的,null == undefined
6. void
It is estimated that there are some small partners might be void
this unfamiliar, that only TypeScript
ago. Actually, it is not. In our JavaScript
, the void
keyword already exists. It means invalid. Some friends may see <a href="javascript: void(0)">
in the earlier project. This is the default behavior that controls the jump of the a
No matter how you execute the void
method, it always returns undefined
So what is the type of void
in our TypeScript
It also represents invalid, generally only used in the function , tell others that this function has no return value.
function fn(): void {} // 正确
function testFn(): void {
return 1; // 报错,不接受返回值存在
}
function fn1(): void { return undefined} // 显示返回undefined类型,也是可以的
function fn2(): void { return null} // 显示返回null类型也可以,因为 null == undefined
7. never
never
a never typed value of or it can be said type executed a never-ending , for there will be no representative of value, undefined
, null
also counted value. Generally this type will not be used or used. Everyone knows this type.
const test: never = null; // 错误
const test1: never = undefined // 错误
function Person(): never { // 正确,因为死循环了,一直执行不完
while(true) {}
}
function Person(): never { // 正确,因为递归,永远没有出口
Person()
}
function Person(): never { // 正确 代码报错了,执行不下去
throw new Error()
}
8. any
any
this type represents any , any . I hope everyone in the project will not define the any
type in large movies. Although it works really well, then we write TypeScript
without any meaning.
let value: any = ""; // 正确
value = null // 正确
value = {} // 正确
value = undefined // 正确
9. unknown
unknown
type is our TypeScript
the second any
type also accepts any value type. Its English translation is unknown , let’s take a look at chestnuts
let value: unknown = ""
value = 1;
value = "fdsfs"
value = null
value = {}
Now there must be some doubts from my friends, eh, then unknown
equivalent to any
, what is the difference between the two. Let's take a look
let valueAny: any = "";
let valueUnknown: unknown = "";
valueAny = "蛙人";
valueUnknown = "前端娱乐圈"
let status: null = false;
status = valueAny; // 正确
status = valueUnknown // 报错,不能将unknown类型分配给null类型
Let's take a look at the above, why the any
type can be assigned successfully, but the unknown
type is not. From the meaning of the two, there is still a little difference, any
any, arbitrary, unknown
unknown. So it doesn't matter if you unknown
type, because it is originally an unknown type. But if you assign its unknown
type to a null
type, then the null
side will not do it, I do not accept the unknown
type.
unknown
, others do not accept the 0612c73ed1eb8e type, and the unknown
type accepts others, hahahaha.
2. Object static type
Speaking of object types, we can definitely think of objects including {}
, array,
class,
function
1. object && {}
In fact, these two mean the same thing. {}
and object
represent non-primitive types, which are types other than number
, string
, boolean
, symbol
, null
or undefined
.
const list: object = {} // 空对象
const list1: object = null; // null对象
const list: object = [] // 数组对象
const list: {} = {}
list.name = 1 // 报错 不可更改里面的字段,但是可以读取
list.toString()
2. Array
const list: [] = []; // 定义一个数组类型
const list1: number[] = [1,2] // 定义一个数组,里面值必须是number
const list2: object[] = [null, {}, []] // 定义一个数组里面必须是对象类型的
const list3: Array<number> = [1,2,3] // 泛型定义数组必须是number类型,泛型我们待会讲到
3. Class
// 类
class ClassPerson = {
name: "前端娱乐圈"
}
const person: ClassPerson = new Person();
person.xxx = 123; // 这行代码报错,因为当前类中不存在该xxx属性
4. Functions
// 函数
const fn: () => string = () => "前端娱乐圈" // 定义一个变量必须是函数类型的,返回值必须是string类型
3. Function type annotation
Here to talk about the function display annotations and function parameters will not type inference problems.
1. The function return type is number
function fn(a, b): number {
return a + b;
}
fn(1, 2)
2. Function void
The display annotation is of void
, and the function has no return value.
function fn(): void {
console.log(1)
}
3. Function does not automatically type inference
You can see that the following function types will not be automatically type deduced. Although our actual parameters are passed in 1 and 2, but the formal parameters can accept any type of value, so the system can't recognize what you pass, so here We need to display and define the annotation type.
function testFnQ(a, b) {
return a + b
}
testFnQ(1,2)
Let's remodel it.
function testFnQ(a:number, b:number) {
return a + b
}
testFnQ(1,2)
Let's take a look at the parameter object display annotation type, and assign each field type after the number :
function testFnQ(obj : {num: number}) {
return obj.num
}
testFnQ({num: 18})
4. Tuple
Tuples are used to represent an array with a known number and type of arrays, and define the type of each value in the array, and are generally not used often.
const arr: [string, number] = ["前端娱乐圈", 1]
const arr: [string, string] = ["前端娱乐圈", 1] // 报错
5. Enumeration
Enum
enumeration type, you can set the default value, if not set, it is the index.
enum color {
RED,
BLUE = "blue",
GREEN = "green"
}
// color["RED"] 0
// color["BLUE"] blue
Like the above color
in RED value is not set, then its value was
0
, if BLUE
not set, then its value is 1
, here they are incremented. If the value is set, it returns the set value
Note that there is another problem here, come directly to the code
Through the above study, we know that enum
can increase the value or set the default value. But one thing to note, enum
not as flexible as the json
enum
cannot be set to a default value on any field.
For example, the following chestnut, RED
has no set value, and then BLUE
set to the default value, but GREEN
is not set, then this GREEN
will report an error. Because your second BLUE
set to the default value, and the third is not set, the code does not know how to increment it, so an error is reported. Another solution is that you BLUE
. At this time, if the third GREEN
not set, it will be incremented because it is of type number
// 报错
enum color {
RED,
BLUE = "blue",
GREEN
}
// good
enum color {
RED, // 0
BLUE = 4, // 4
GREEN // 5
}
For example, the enum
enumeration type can also be contrasted. Check the value key
value
Objects like our json
do not support this writing.
enum color {
RED, // 0
BLUE = 4, // 4
GREEN // 5
}
console.log(color[4]) // BLUE
console.log(color[0]) // RED
5. Interface
What is the interface interface
interface
is convenient for us to define one code and reuse it in multiple places. There are also some modifiers in the interface. Let's get to know them.
1. How to reuse the interface
For example, before we talk about this, we don't know the interface. If you need to define a type for the object, you might do this.
const testObj: { name: string, age: number } = { name: "前端娱乐圈", age: 18 }
const testObj1: { name: string, age: number } = { name: "蛙人", age: 18 }
Let's use the interface to transform it.
interface Types {
name: string,
age: number
}
const testObj: Types = { name: "前端娱乐圈", age: 18 }
const testObj1: Types = { name: "蛙人", age: 18 }
You can see that the interface
keyword is used to define an interface, and then assign values to these two variables to achieve reuse.
2. The readonly modifier
readonly
type, only readable status, unchangeable.
interface Types {
readonly name: string,
readonly age: number
}
const testObj: Types = { name: "前端娱乐圈", age: 18 }
const testObj1: Types = { name: "蛙人", age: 18 }
testObj.name = "张三" // 无法更改name属性,因为它是只读属性
testObj1.name = "李四" // 无法更改name属性,因为它是只读属性
3.? Optional modifier
Optional modifiers are ?
. Why do we need optional modifiers? Because if we don’t write optional modifiers,
interface
are all required.
interface Types {
readonly name: string,
readonly age: number,
sex?: string
}
const testObj: Types = { name: "前端娱乐圈", age: 18}
4. extends inheritance
Our interface
can also be inherited, just like the ES6 Class
class, using the extends
keyword.
interface Types {
readonly name: string,
readonly age: number,
sex?: string
}
interface ChildrenType extends Types { // 这ChildrenType接口就已经继承了父级Types接口
hobby: []
}
const testObj: ChildrenType = { name: "前端娱乐圈", age: 18, hobby: ["code", "羽毛球"] }
5. propName extension
This function in interface is very powerful, it can write attributes that are not in interface.
interface Types {
readonly name: string,
readonly age: number,
sex?: string,
}
const testObj: Types = { name: "前端娱乐圈", age: 19, hobby: [] }
The above testObj
line of code will become hobby
because the 0612c73ed1f233 attribute does not exist in the interface
interface, so don’t let people write it in the interface that does not exist? . This can be used when custom is above propName
.
interface Types {
readonly name: string,
readonly age: number,
sex?: string,
[propName: string]: any // propName字段必须是 string类型 or number类型。 值是any类型,也就是任意的
}
const testObj: Types = { name: "前端娱乐圈", age: 19, hobby: [] }
After running the above code, you can see that it is not popular~
6. Type
Let's look at Type
. This is used to declare type aliases. The alias type can only be defined as: basic static type,
object static type,
tuple,
union type.
Note: type alias cannot define interface
type Types = string;
type TypeUnite = string | number
const name: typeUnite = "前端娱乐圈"
const age: typeUnite = 18
1. So what is the difference between type type alias and interface interface?
1. Type does not support interface declaration
type Types = number
type Types = string // 报错, 类型别名type不允许出现重复名字
interface Types1 {
name: string
}
interface Types1 {
age: number
}
// interface接口可以出现重复类型名称,如果重复出现则是,合并起来也就是变成 { name:string, age: number }
The first Types
type alias type does not allow duplicate names, and the interface interface can have duplicate type names. If they are duplicated, they will be changed to { name:string, age: number }
take a look at another case of interface
interface Types1 {
name: string
}
interface Types1 {
name: number
}
You can see that the above two interface
interfaces with the same name have the same attributes but different types. This is the second of Types1
will be booming and tips: Interface subsequent declaration, must be declared with the same name in front of the property type must be consistent , the subsequent declaration of name
its type into string
can be.
2. Type support expression interface does not support
const count: number = 123
type testType = typeof count
const count: number = 123
interface testType {
[name: typeof count]: any // 报错
}
You can see that the above type
supports expressions, but interface
does not support
3. Type supports type mapping, interface does not support
type keys = "name" | "age"
type KeysObj = {
[propName in keys]: string
}
const PersonObj: KeysObj = { // 正常运行
name: "蛙人",
age: "18"
}
interface testType {
[propName in keys]: string // 报错
}
7. Joint Type
joint type is
|
. To put it plainly, it is enough to satisfy one of the types.
const statusTest: string | number = "前端娱乐圈"
const flag: boolean | number = true
Let's look at chestnuts again. We use the function parameter to use the union type see what happens
function testStatusFn(params: number | string) {
console.log(params.toFixed()) // 报错
}
testStatusFn(1)
As we said above, function parameter types cannot be automatically deduced. What's more, now using combined type , the system is even more confusing and cannot recognize the type of the current actual parameter. Therefore, an error is reported when accessing the method on the current type.
Next, I will show you some type protections. They sound very advanced, but in fact, everyone has seen them. Don’t forget to pay attention to: Front-end entertainment circle public account Oh, hee hee
1. typeof
function testStatusFn(params: number | string) {
console.log(params.toFixed()) // 报错
}
testStatusFn(1)
after transformation
// 正常
function testStatusFn(params: string | number) {
if (typeof params == "string") {
console.log(params.split)
}
if (typeof params == "number") {
console.log(params.toFixed)
}
}
testStatusFn(1)
2. in
// 报错
interface frontEnd {
name: string
}
interface backEnd {
age: string
}
function testStatusFn(params: frontEnd | backEnd) {
console.log(params.name)
}
testStatusFn({name: "蛙人"})
after transformation
// 正常
function testStatusFn(params: frontEnd | backEnd) {
if ("name" in params) {
console.log(params.name)
}
if ("age" in params) {
console.log(params.age)
}
}
testStatusFn({name: "蛙人"})
3. as assertion
// 报错
interface frontEnd {
name: string
}
interface backEnd {
age: string
}
function testStatusFn(params: frontEnd | backEnd) {
console.log(params.name)
}
testStatusFn({name: "蛙人"})
after transformation
// 正常
function testStatusFn(params: frontEnd | backEnd) {
if ("name" in params) {
const res = (params as frontEnd).name
console.log(res)
}
if ("age" in params) {
const res = (params as backEnd).age
console.log(res)
}
}
testStatusFn({age: 118})
8. Crossover type
cross type is the opposite of the union type. It is
&
. The cross type means that two types must exist. Here also use the above combined type chestnuts to look at.
interface frontEnd {
name: string
}
interface backEnd {
age: number
}
function testStatusFn(params: frontEnd & backEnd) {}
testStatusFn({age: 118, name: "前端娱乐圈"})
Here we can see that the actual parameters must be passed in all the attribute values of the interfaces (interface) joint type be passed into the type.
Note: Our interface has the same name attribute
interface frontEnd {
name: string
}
interface backEnd {
name: number
}
function testStatusFn(params: frontEnd & backEnd) {
console.log(params)
}
testStatusFn({name: "前端"})
The attributes with the same name appear in both of our interface types above, but the types are different. At this time, the type will become never
.
<img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/51e337707b6641e590bbb0139fabacdb~tplv-k3u1fbpfcp-watermark.image" width="90%">
9. Generic
Generics are the TypeScript
in an easy-to-understand way.
function test(a: string | number, b: string | number) {
console.log(a, b)
}
test(1, "前端娱乐圈")
For example, in the above chestnut, the function parameter annotation type definition
string
and number
, there is no problem in calling the function argument, but there is a requirement, that is, the actual parameter must be passed in the same type (pass in two number
types). Although the above union type can also be implemented, but if we want to add a boolean
type, then the union type has to add a boolean
, then the code is too redundant.
At this time, you need to use the generic , and the generic is used specifically for uncertain types and is flexible. Most of the use of generics is <T>
, of course, you can also use it casually, such as: <Test>
, <Custom>
.
function test<T>(a: T, b: T) {
console.log(a, b)
}
test<number>(1, "前端娱乐圈") // 调用后面跟着尖括号这就是泛型的类型,这时报错,因为在调用的使用类型是number,所以只能传入相同类型的
test<boolean>(true, false)
test<string>("前端娱乐圈", "蛙人")
The above uses the generic to solve the problem of passing in the same type parameter we just said, but the generic can also use different parameters, and the call type can be defined as <any>
function test<T>(a: T, b: T) {
console.log(a, b)
}
test<any>(1, "前端娱乐圈")
But there is another problem with the above, it can pass in objects, but if we only want to pass in number
type and string
type. Then our generic also provides us with constraint
type. Generic uses extends
carry out type constraint string
, number
type can be selected.
function test<T extends number | string, Y extends number | string>(a: T, b: Y) {
console.log(a, b)
}
test<number, string>(18, "前端娱乐圈")
test<string, number>("前端娱乐圈", 18)
At this time, use ,
separate the generic type to define what each type hopes to be. Remember, only the types that we are not sure of can use generics.
10. Module
TypeScript
also supports import
and export
. Most of the friends here know, so I won't talk about it here.
// 导入
import xxx, { xxx } from "./xxx"
// 导出
export default {}
export const name = "前端娱乐圈"
If you have any friends who don’t understand, you can read my previous article talk about CommonJs and Es Module and the difference between them
11. Class
The following three modifiers isTypeScript
to use in class, inJavaScript
class is not supported.
1. public
public
to class public property, that is, whether in
inside or outside the class can access the
class property and method . The default defined attribute and method are both
public
.
class Person {
name = "前端娱乐圈";
public age = 18;
}
const res = new Person();
console.log(res.name, res.age) // 前端娱乐圈 18
The results can be seen above print displayed, name
attribute is not defined public
public property, so inside the class definition property and method default is
public
definition.
2. private
private
to class of private property, and only in the current
to access inside the class, the current
class is
{}
in the inside area. In {}
outside is not accessible private
defined properties and method of
class Person {
private name = "前端娱乐圈";
private age = 18;
}
const res = new Person();
console.log(res.name, res.age) // 这俩行会爆红,当前属性为私有属性,只能在类内部访问
class Scholl extends Person {
getData() {
return this.username + "," + this.age
}
}
const temp = new Scholl()
console.log(temp.getData()) // 爆红~,虽然继承了Person类,但是private定义是只能在当前类访问,子类也不能访问。
3. protected
protected
is the protection attribute of the class, which can only be accessed current class and the subclass That is to say, the subclass
protected
attribute can also be accessed.
class Person {
protected username = "前端娱乐圈";
protected age = 18;
}
const res = new Person();
console.log(res.name, res.age) // 这俩行会爆红,当前属性为私有属性,只能在类内部访问
class Scholl extends Person {
getData() {
return this.username + "," + this.age
}
}
const temp = new Scholl()
console.log(temp.getData()) // 前端娱乐圈,18。可以正常访问父类的属性
4. implements
implements
keyword can only be used in class
. As the name implies, a new class is implemented. All properties and methods are implemented from the parent or from the interface. If you do not write the existing properties and methods in the interface PersonAll
.
interface frontEnd {
name: string,
fn: () => void
}
class PersonAll implements frontEnd {
name: "前端娱乐圈";
fn() {
}
}
5. Abstract class
The abstract class is abstract
keyword. abstract
abstract method cannot be instantiated. If the method in the abstract class is abstract, then the class itself must also be abstract, and the abstract method cannot write the function body. There is an abstract method in the parent class, so the subclass must also renew the method.
// 抽象类
abstract class Boss {
name = "秦";
call() {} // 抽象方法不能写函数体
}
class A extends Boss {
call() {
console.log(this.name);
console.log("A")
}
}
class B extends Boss {
call() {
console.log("B")
}
}
new A().call()
The abstract class usage scenarios, such as the A
requirement or the B
requirement, just need a public attribute, and then there is some logic of its own, you can use the abstract class, and the abstract class can only be used in TypeScript
.
12. Namespace namespace
As we have learned, we can see that, I don’t know if you guys found out whether the files in the project can’t have duplicate variables (regardless of whether you are the same file or other files), otherwise it will be directly popular. One of the most explicit purpose of namespace is to solve the problem of duplicate names.
The namespace namespace
look at chestnuts.
index.ts
namespace SomeNameSpaceName {
const q = {}
export interface obj {
name: string
}
}
In the above, a namespace is defined. You can see that the variable q
does not write the export
keyword, which proves that it is an internal variable. Even if other .ts
files refer to it, it will not be exposed. And interface
this obj
interfaces can be globally accessible.
We visit the current namespace on another page
1. Reference introduction
/// <reference path="./index.ts" />
namespace SomeNameSpaceName {
export class person implements obj {
name: "前端娱乐圈"
}
}
2. import
export interface valueData {
name: string
}
import { valueData } from "./xxx.ts"
At this time, the use of namespaces can completely solve the problem of the repeated names of different files.
13. tsConfig.json
This tsconfig
file is how we compile the ts file, how to ts
file into our js
file. tsc -init
This command will generate the file out. After executing this command, we can see that a tsconfig.json
file will be generated in the root directory with a bunch of attributes.
So how will we ts
documents translated into js
file it directly execute tsc
command to all of the root directory .ts
all the documents compiled .js
output file to the project.
For more configuration documents, please refer to official website
{
// include: ["*.ts"] // 执行目录下所有的ts文件转换成js文件
// include: ["index.ts"] // 只将项目下index.ts文件转换为js文件
// files: ["index.ts"] // 跟include一样,只执行当前数组值里面的文件,当前files必须写相对路径
// exclude: ["index.ts"] // exclude就是除了index.ts不执行,其它都执行
compilerOptions: {
removeComments: true, // 去掉编译完js文件的注释
outDir: "./build", // 最终输出的js文件目录
rootDir: "./src", // ts入口文件查找
}
}
8. Practical type
TypeScript
about practical types. The 0612c73ed1fff4 standard library comes with some practical types. These utility classes are convenient to use with the Interface
Here are just a few commonly used, more practical types official website
1. Exclude
Excluding one type from another type can only be combined type , and TypesTest
type excluded from UtilityLast
type.
applies to:
interface UtilityFirst {
name: string
}
interface UtilityLast {
age: number
}
type TypesTest = UtilityFirst | UtilityLast;
const ObjJson: Exclude<TypesTest, UtilityLast> = {
name: "前端娱乐圈"
}
2. Extract
Extract
just the opposite with the above, it is to select one assignable union type , from TypesTest
select only the type UtilityLast
type.
applies to:
interface UtilityFirst {
name: string
}
interface UtilityLast {
age: number
}
type TypesTest = UtilityFirst | UtilityLast;
const ObjJson: Extract<TypesTest, UtilityLast> = {
age: 1
}
3. Readonly
Convert all attribute values of an array or object to read-only. Here only demonstrate the same way of writing object chestnuts and arrays.
applies to: objects, arrays
interface UtilityFirst {
name: string
}
const ObjJson: Readonly<UtilityFirst> = {
name: "前端娱乐圈"
}
ObjJson.name = "蛙人" // 报错 只读状态
4. Partial
Set all the properties of the object as optional. We know interface
they do not set ?
modifier, then the object is mandatory. This utility class can convert all attributes to optional.
applies to: Object
interface UtilityFirst {
name: string
}
const ObjJson: Partial<UtilityFirst> = {
}
5. Pick
Pick
Select part of the key
value in the object type and extract it. The first parameter target value, the second parameter combined with
key
applies to: object
interface UtilityFirst {
name: string,
age: number,
hobby: []
}
const ObjJson: Pick<UtilityFirst, "name" | "age"> = {
name: "前端娱乐圈",
age: 18
}
6. Omit
Omit
Select part of the key
value in the object type and filter it out. The first parameter target value, the second parameter combined with
key
applies to: object
interface UtilityFirst {
name: string,
age: number,
hobby: string[]
}
const ObjJson: Omit<UtilityFirst, "name" | "age"> = {
hobby: ["code", "羽毛球"]
}
7. Required
Required
converts all optional attributes of the object into mandatory attributes.
Applies to: Object
interface UtilityFirst {
name?: string,
age?: number,
hobby?: string[]
}
const ObjJson: Required<UtilityFirst> = {
name: "蛙人",
age: 18,
hobby: ["code"]
}
8. Record
Create an object result set, the first parameter is the key
, and the second parameter is the value value
It is stipulated that we can only create the value of this field.
applies to: object
type IndexList = 0 | 1 | 2
const ObjJson: Record<IndexList, "前端娱乐圈"> = {
0: "前端娱乐圈",
1: "前端娱乐圈",
2: "前端娱乐圈"
}
grateful
Thank you for reading this article. I hope it will be helpful to you. If you have any questions, please correct me.
I’m a frogman. If you think it’s okay to write, please give me a thumbs up ❤.
Interested friends can join [Front-end entertainment circle exchange group] Welcome everyone to exchange and discuss
Writing is not easy, "Like" + "Watching" + "Repost" Thank you for your support ❤
The next update of TypeScript actual combat, welcome to pay attention
Reference
- https://www.cnblogs.com/mengff/p/12936795.html
- TypeScript introductory tutorial
- TypeScript programming entity book
- TypeScript Chinese website
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。