TypeScript is a superset of JavaScript that supports the ECMAScript 6 standard ( ES6 tutorial ).
TypeScript is a free and open source programming language developed by Microsoft.
The design goal of TypeScript is to develop large-scale applications, which can be compiled into pure JavaScript, and the compiled JavaScript can run on any browser.
Article Directory
1 TypeScript VS JavaScript
TypeScript | JavaScript |
---|---|
A superset of JavaScript for addressing the code complexity of large projects | A scripting language used to create dynamic web pages |
Strong typing, supports static and dynamic typing | Dynamic weakly typed language |
Errors can be found and corrected during compilation | Errors can only be found at runtime |
It is not allowed to change the data type of the variable | Variables can be assigned different types |
2 TypeScript basics
2.1 TS Foundation - Foundation Type
- boolean、number、string
- undefined、null
- any、unknown、void
- never
- ArrayType[]
- tuple type tuple
// 举个例子
function test(x:string | number):boolean {
if (typeof x === 'string') {
return true;
} else if (typeof x === 'number') {
return false;
}
return throwError('参数格式不对');
}
function throwError(message:string):never {
throw new Error(message);
}
2.2 TS basics - function type
Definition: TS defines the input parameter type and output type when defining the function type
Input parameters: parameters support optional parameters and default parameters
Output parameters: the output can be inferred automatically, and when there is no return value, the default is void type
Function overloading: same name but different parameters, multiple types can be supported through overloading
function add(x:number[]):number
function add(x:string[]):string
function add(x:any[]):any {
if (typeof x[0] === 'string') {
return x.join()
}
if (typeof x[0] === 'number') {
return x.reduce((acc,cur) => acc + cur)
}
}
2.3 TS basic-interface
Definition: Interfaces are used to define object types
Features:
- Optional attributes: ?
- Read-only attribute: readonly
- can describe the function type
- Can describe custom properties
Summary: The interface is very flexible duck typing
interface RandomKey {
[propName:string]:string
}
const obj:RandomKey = {
a:'hello',
b:'world',
c:'typescript',
}
2.4 TS Basics - Classes
Definition: The writing method is similar to JS, with some definitions added
Features:
- Added public, private, protected modifiers
- Abstract class:
- Can only be inherited, not instantiated
- As a base class, abstract methods must be implemented by subclasses
- interface: constraint class, use the implements keyword
3 Advanced TypeScript
3.1 TS Advanced - Advanced Type
- union type |
- cross type &
- type assertion
- Type aliases (type VS interface)
- Definition: aliasing a type
- Same point:
- Both can define objects or functions
- Both allow inheritance
- difference
- interface is used by TS to define objects, and type is used to define aliases for easy use;
- type can define basic types, interface: no;
- Interface can merge repeated declarations, but type cannot;
3.2 TS Advanced - Generics - When do you need generics?
Official definition:
In software engineering, we not only have to create consistent well-defined APIs, but also consider reusability.
Components can not only support current data types, but also support future data types, which provides you with very flexible functions when creating large-scale systems.
In languages like C# and Java, generics can be used to create reusable components,
A component can support multiple types of data. This allows users to use components with their own data types.
It's a bit obscure, let's give a chestnut.
3.3 TS Advanced - Generics - When do you need generics?
3.4 TS Advanced - Generics - Basic Use
Basic definition:
- The syntax of generics is ◇Writing type parameters in it, generally represented by T;
- There are two ways to specify the type when using:
- Define the type to use
- Through TS type inference, automatically deduce the type
- The role of generics is to temporarily occupy the place, and then deduce it through the passed type;
function print<T>(arg:T):T {
console.lLog(arg)
return arg
}
print<string>('hello') // 定义T为string
print('hello') // TS类型推断,自动推导类型为string
3.5 TS Advanced - Generic Tool Type - Basic Operators
3.6 TS Advanced - Generic Tool Types - Common Tool Types
- Partials: Make type properties optional
- Required: Make the type attribute mandatory
- Readonly.: Make the type property read-only
- Pick、Record…
type Partials<T> ={
[P in keyof T]?:T[P];
};
type Required<T> = {
[P in keyof T]-?:T[P]
};
type Readonly<T> = {
readonly [P in keyof T]:T[P];
};
4 TypeScript in action
4.1 TS actual combat - statement file
- declare: The three-party library requires a type declaration file
- .dts: declaration file definition
- @types: Three-party library TS type package
- tsconfig.json: Define the configuration of TS