当前位置:网站首页>Basic explanation of typescript
Basic explanation of typescript
2022-07-05 06:11:00 【Crisp bamboo book pavilion under the moon】
TypeScript Basic explanation
Type notes
/** * Type notes : Add type constraints to variables * let Variable name : type = Initial value */
let age:number = 18;
age = 123;
TS type
/** * ts type : * The original type :number/string/boolean/null/undefined/symbol * object type :object( Array 、 object 、 function ) * newly added ts type : * Joint type * Custom type * Interface * Tuples * Literal type * enumeration * void * any */
let num:number = 18; // value type
let myName:string = " Zhang San ";// String type
let isLoading:boolean = true;// Boolean type
let un:undefined = undefined;//undefined
let timer:null = null;//null
let sym:symbol = Symbol();
TS Type inference mechanism
/** * TS The type inference mechanism will automatically provide the type * as follows a The default is number type * add The default is number type */
let a = 1;
function add(a:number,b:number){
return a+b;
}
Joint type
/** * Joint type : When a value can be either number type It may also be for null when , You need a new type * ( The variable can be null perhaps number type ) */
let unite:number|null = null;
unite = 2;
Type the alias
/** * Type the alias : When the defined type name is very long , You can define aliases , Easy to write ( title case !!--NewType) * effect : * 1. Alias the definition * 2. Defines a new type */
type StringNumber = string | number;
let myColor:StringNumber = "red";
myColor = 124;
An array type
/** * An array type * How to write it 1:let num: type []= [ value 1,...] * How to write it 2:let num:Array< type > = [ value 1,...]; * */
// How to write it 1
let numbers:number[] = [1,2,3,4];
// How to write it 2
let strings:Array<string> = ['1','2','3'];
function
/** * function * Function type : Function parameter type 、 return type * Ordinary function :function Function name ( Shape parameter 1: type = The default value is , Shape parameter 2: type = The default value is , Shape parameter 3: type = The default value is ): return type {} * Arrow function :function Function name ( Shape parameter 1: type = The default value is , Shape parameter 2: type = The default value is , Shape parameter 3: type = The default value is ): return type =>{} * * Uniformly define the function format : When the types of functions are consistent , Writing more than one will make the code redundant , Therefore, the format of the function needs to be defined uniformly * * If there is no return value type , Should use the void * Situation 1 : Function didn't write return * Situation two : Only written. return, No specific return value * Situation three :return The return is undefined * * Function optional parameters : Parameters can be transferred or not !! Mandatory parameters cannot follow optional parameters * fucntion slice(a?:number,b?number) * */
// Ordinary function
function add1(num1: number, num2: number): number {
return num1 + num2
}
// Arrow function
const add2 = (a: number =100, b: number = 100): number =>{
return a + b
}
// Define a function type uniformly
type Fn = (n1:number,n2:number) => number ;
const add3 : Fn = (a,b)=>{
return a+b }
//============================ The return value is void============
// The return value is void
function greet(name:string= "1234"):void{
console.log("hello",name);
}
// If you don't write anything , here ,add The return value type of the function is : void
const add4 = () => {
}
// If return Then I don't write anything , here ,add The return value type of the function is : void
const add5 = () => {
return }
const add6 = (): void => {
// here , Back to undefined yes JS A value of
return undefined
}
// This way of writing is to explicitly specify that the return value type of the function is void, Same as the return value type not specified above
const add7 = (): void => {
}
// Mandatory parameters cannot follow optional parameters Don't write like this !!.
// function mySlice(start?:number,end:number){}
object type
/** * object type * const Object name = { * Property name 1: type 1, * Property name 2?: type 2, * Method name 1( Shape parameter 1: type 1, Shape parameter 2: type 2): return type , * Method name 2:( Shape parameter 1: type 1, Shape parameter 2: type 2) => return type * } = { Property name 1: value 1, Property name 2: value 2 } */
// Create type aliases
type Person = {
name:string,
age:number,
sayHi():void
}
// Use the type alias as the type of the object
let person:Person={
name:"xiaohua",
age:18,
sayHi(){
}
}
Interface
/** * Interface : When an object type is used more than once , There are two ways to describe the types of objects , To achieve reuse : * 1. Type the alias :type * 2. Interface :interface * grammar :interface The interface name { attribute 1: type 1, attribute 2: type 2, attribute 3: type 3} * * * type And interface The difference between * - The same thing : You can assign types to objects * - Difference : * - Interface : Only type can be specified for an object ,【 Inherit 】 * - Type the alias : You can not only specify the type of object , You can also be right about 【 Any type 】 Specify alias * First of all interface, After that type, Recommended type * * Interface inheritance * If two interfaces have the same properties or methods , Can be 【 Public properties or methods are extracted , Reuse through inheritance 】 * interface Interface 2 extends Interface 1{ * attribute 1: type 1 // Interface 2 The unique type of * } */
// Use interface Declare interface
interface IGoodItem{
name:string,
age:number,
func:()=>string,
func1():string
}
// Use the interface name as the variable type
const good1:IGoodItem = {
name:" floret ",
age:18,
func:function(){
return "123"
},
func1:()=>{
return "124"
}
}
//============= Interface inheritance =============
interface a {
x:number,
y:number
}
// Use extends( Inherit ) Keyword implements the interface
interface b extends a {
z:number
}
//b Inherited a, That explains. b Have the a All properties and methods of
Tuples
/** Don't understand, ; * Tuples : It's a special kind of array , The special point is the following two points * - It stipulates the number of elements * - It specifies the data type corresponding to a specific index * */
function useState(n: number): [number, (number)=>void] {
const setN = (n1) => {
n = n1
}
return [n, setN]
}
const [num1 ,setNum] = useState(10)
Literal type
/** * Literal type * effect : Often used with union types * */
//str1, It's a variable , Its value can be any character , So the type is string
//str2 Is a constant , His value cannot change , Can only be "Hello TS", So his type is "Hello TS",
// Well, here "Hello TS" It's a literal type , In other words, a specific string can also be used as TS The type of
let str1:string ="hello";
const str2 ="Hello TS";
// Matching joint type
type Gender = 'girl' | 'boy'
// Declare a type , His value yes 'girl' Or is it 'boy'
let g1: Gender = 'girl' // correct
let g2: Gender = 'boy' // correct
// let g3: Gender = 'man' // error
/** * enumeration : Be similar to 【 Literal type + Joint type 】, To describe a value * enum Enum name { Value for 1, Value for 2...} * Usage mode : Enum name . Value for 1 * Be careful : * 1. Generally, enumeration names begin with uppercase letters * 2. Multiple values in the enumeration are marked with commas , Division * 3. After defining the enumeration , Directly use enumeration names as type annotations * * Enumeration types are divided into : Numeric enumeration and string enumeration * - Numerical enumeration : The default is 0 Start self increasing value , You can also initialize values for members in the enumeration */
enum Eunm1 {
up,down,left,right};
Eunm1.up;
// Numerical enumeration Custom initial value
enum Direction1 {
Up = 10, Down, Left, Right };// Down -> 11、Left -> 12、Right -> 13
enum Direction2 {
Up = 2, Down = 3, Left = 8, Right = 16 }
// String Enum ( Each member must have an initial value )
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
}
any
/** * any: Any of the , Remove type restrictions * Use scenarios : * - function * - Come on “ avoid ” Writing is long 、 Very complex type * - Declared variables do not provide types or default values * - When defining a function , Parameter does not give type * */
边栏推荐
- Introduction to LVS [unfinished (semi-finished products)]
- 对for(var i = 0;i < 5;i++) {setTimeout(() => console.log(i),1000)}的深入分析
- 1040 Longest Symmetric String
- Liunx starts redis
- QT判断界面当前点击的按钮和当前鼠标坐标
- [practical skills] technical management of managers with non-technical background
- Leetcode-556: the next larger element III
- LVS简介【暂未完成(半成品)】
- Dynamic planning solution ideas and summary (30000 words)
- MIT-6874-Deep Learning in the Life Sciences Week 7
猜你喜欢
Leetcode-6111: spiral matrix IV
Sqlmap tutorial (1)
数据可视化图表总结(二)
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
6. Logistic model
[jailhouse article] look mum, no VM exits
MatrixDB v4.5.0 重磅发布,全新推出 MARS2 存储引擎!
MIT-6874-Deep Learning in the Life Sciences Week 7
R language [import and export of dataset]
[practical skills] how to do a good job in technical training?
随机推荐
CF1637E Best Pair
Data visualization chart summary (I)
Navicat連接Oracle數據庫報錯ORA-28547或ORA-03135
Groupbykey() and reducebykey() and combinebykey() in spark
Arduino 控制的 RGB LED 无限镜
【实战技能】如何做好技术培训?
Daily question 1688 Number of matches in the competition
【云原生】微服务之Feign自定义配置的记录
1041 Be Unique
leetcode-9:回文数
[practical skills] technical management of managers with non-technical background
leetcode-3:无重复字符的最长子串
1041 Be Unique
liunx启动redis
A reason that is easy to be ignored when the printer is offline
R语言【数据集的导入导出】
The sum of the unique elements of the daily question
MIT-6874-Deep Learning in the Life Sciences Week 7
[rust notes] 16 input and output (Part 2)
Control unit