ts basic content

  1. javascript scripting language
  2. Abbreviated as ts for javascript advanced script syntax

TypeScript is an open source programming language developed by Microsoft , built by adding static type definitions on top of JavaScript . TypeScript is translated into JavaScript code through the TypeScript compiler or Babel, and can run on any browser and any operating system.

 
 
  1. TypeScript中文网 · TypeScript——JavaScript的超集

official website

 
 
  1. https://www.tslang.cn/index.html

The difference between ts and js

TypeScript is a superset of JavaScript that extends the syntax of JavaScript, so existing JavaScript code can work with TypeScript without any modification. TypeScript provides compile-time static type checking through type annotations.

language features

TypeScript is a language extension that adds features to JavaScript. Added features include:

 
 
类型批注和编译时类型检查
类型推断
类型擦除
接口
枚举
Mixin
泛型编程
名字空间
元组
Await
以下功能是从 ECMA 2015 反向移植而来:

类
模块
lambda 函数的箭头语法
可选参数以及默认参数

type

 
 
类型分析:强类型 和 弱类型
变量在声明之后 是否可以任意转化数据类型
js 弱类型脚本语言 动态弱类型检测
ts 弱类型脚本语言 静态弱类型检测

document

 
 
  1. https://typescript.bootcss.com/

Use ts outside the project

 
 
  1. npm install -g typescript

Use ts compiler to compile

 
 
  1. tsc 文件名称

Files are created with ts suffix

 
 
  1. index.ts

The ts file cannot be used directly in the browser, it needs to be compiled and accessed by the browser

 
 
ts/ts 区别

ts代码
let sname:string = "";
sname = 'a';


js
let sname = "";
sname = 1;

//编译之后的
var sname = "";
sname = "a";

syntax in ts

 
 
类型
//ts 声明变量 关键词 名称:类型=初试值?
//字符串类型
let sname: string = "a";
let ssname: string;

//bool
let isM: boolean = true;

//number
let age: number = 0;

//数组
let arr: string[] = [];
let arr1: number[] = [];
let arr2: boolean[] = [];
let arr3: object[] = [];

//泛型
let arr4: Array<number> = [];

//元组
let a: [string, number] = ["a", 1];
console.log(a);

//枚举
enum week {
"mon",
"tus" = 10,
"wed",
}

console.log(week);
console.log(week[0]);

//任意值
let b: any[] = [1, "a", true];
let c: any = "a";

//void 空值 无返回值类型 函数使用
function Person(): void {}
function Person1(): boolean {
return true;
}

//undefined null
let u: undefined = undefined;
let n: null = null;

type assertion

 
 
在代码中如果存在一个变量可能有值或者为null
data.id-----data 可能有值或者为null
使用类型断言处理

This is the way to tell the compiler, "trust me, I know what I'm doing" through type assertions . Type assertions are like type conversions in other languages

type assertion as

 
 
//类型断言
let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;
let strLength: number = (<string>someValue).length;

Specifically use vite to build the react ts project:

 
 
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

function

Function type annotation

 
 
ts在函数的形参上添加了类型,并且函数需要带返回值类型

function Person(name:string):void{

}

Complete writing of ts function

Add function expressions to functions

 
 
(str: string) => number 为函数类型
这种写法更像变量赋值
let Lens: (str: string) => number = function (str: string): number {
return str.length;
};

Optional arguments and default values ​​for functions

 
 
//?为可选
function add(a: number, b?: number): number {
if (b) {
return a + b;
}
return a;
}

add(1);
// function add(a: number, b: number = 0): number {
// return a + b;
// }

// add(1);


function Save(a: string, ...b: string[]) {
console.log(b);
}
Save("a", "b", "c");

overload

JavaScript itself is a dynamic language. It is very common in JavaScript for functions to return different types of data depending on the parameters passed in.

What is more overloaded?

Functions with the same name, different numbers of parameters, and different types of return values ​​are called function overloading.

 
 
//重载
//重载个数算函数表达式
//函数的主题必须兼容上面的表达式
function Sort(): string[];
function Sort(a: string): string[];
function Sort(a: string, b: string): string[];
function Sort(a: number, b: number): number[];
//函数主体
function Sort(a?: any, b?: any): any[] {
if (typeof a == "number" && typeof b == "number") {
return [b, a];
}
if (typeof a == "string" && typeof b == "string") {
return [b, a];
}
return [];
}

Sort(1, 2);

//编译之后
//函数主体
function Sort(a, b) {
if (typeof a == "number" && typeof b == "number") {
return [b, a];
}
if (typeof a == "string" && typeof b == "string") {
return [b, a];
}
return [];
}
Sort(1, 2);

custom type in ts

use the type keyword

 
 
//自定义类型
type PropType = {
name: string;
age?: number;
};

//以上定义的格式 直接定义属性为必填 写?属性为选填

let stu: PropType = { name: "" };

Take the project as an example:

 
 
const App = () => {
return (
<>
<div>app</div>
</>
);
};

export default App;
//普通的函数组件

转化为ts格式组件
import React from "react";
//使用type定义props
type PropTypes = {
list?: object[];
};

const Menu: React.FC<PropTypes> = (props) => {
return (
<>
<div>Menu</div>
</>
);
};
//props默认值
Menu.defaultProps = {
list: [],
};

export default Menu;

interface

interface

One of the core principles of TypeScript is type checking the structure a value has . It is sometimes called "duck typing" or "structural subtyping". In TypeScript, the role of interfaces is to name these types and define contracts for your code or third-party code.

Both type and interface in ts can be structured.

 
 
interface 关键词
//接口的作用 定义结构 没有实现体
interface propsTypes {
name: string;
age: number;
fun: () => void;
}

//对象实现接口
let stus: propsTypes = {
name: "小花",
age: 18,
fun:function ():void{

}
};

//接口属性选填
let app:()=>number=function():number{

}
直接在属性上写?
interface propsTypes {
name: string;
age: number;
fun?: () => void;//选填
}

//对象实现接口
let stus: propsTypes = {
name: "小花",
age: 18,
};

interface read only

 
 
关键词 readonly
interface propsTypes {
name: string;
age: number;
fun?: () => void;
readonly goback: boolean;
}

//对象实现接口
let stus: propsTypes = {
name: "小花",
age: 18,
goback: true,
};

//接口定义的属性 不能赋值
// stus.goback = false;

Set any property in the interface

 
 
接口背实现之后如果没有设置任意,不能随意添加属性。
//接口的作用 定义结构 没有实现体
interface propsTypes {
name: string;
age: number;
fun?: () => void;
readonly goback: boolean;
//任意
[propName: string]: any; //值 any
}

//对象实现接口
let stus: propsTypes = {
name: "小花",
age: 18,
goback: true,
isma: false,
isFUN: 10,
};

//接口定义的属性 不能赋值
// stus.goback = false;

interface indexing

 
 
interface aType {
//index 为固定
[index: number]: string;
}
let arrss: aType = ["a"];

Modify the function component props to use the interface interface

 
 
import React from "react";
//使用type定义props
// type PropTypes = {
// list?: object[];
// };

type listType = {
id: number;
name: string;
};

interface PropTypes {
list?: object[];
}

const Menu: React.FC<PropTypes> = (props) => {
return (
<>
<div>Menu</div>
</>
);
};
//props默认值
Menu.defaultProps = {
list: [],
};

export default Menu;

ts operation function component

 
 
1.文件后缀为tsx
2.写函数组件
3.修改为ts
import React, { MouseEvent, ReactElement, useState } from "react";
//接口
//限定结构
type menuType = {
name?: string;
};
interface propTypes {
menu: menuType[];
children?: ReactElement;
}
const Menu: React.FC<propTypes> = ({ menu, children }) => {
let [isShow, setShow] = useState<boolean>(true);

let add = (e: MouseEvent) => {
console.log(1111);
};
if (isShow) {
return (
<>
<div>
<button onClick={add}>按钮</button>
{menu.map((item, index) => {
return <p key={index}>{item.name}</p>;
})}
</div>
</>
);
}
return null;
};

export default Menu;

generic

In software engineering, we not only 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.

Explanation: You don't need to know the type when you define it, and tell the type when you use it.

 
 
举例:
function identity(arg: number): number {
return arg;
}

function identity(arg: any): any {
return arg;
}

//以上两种函数 同名 参数类别不一致 返回值不一致。
//会定义多个导致函数的可复用性变差。

使用泛型提高函数可复用性

使用泛型变量来定义泛型结构

function psy<T>(a: T): T {
return a;
}

psy<number>(1);
psy<string>("a");
psy<boolean>(true);


//使用泛型变量
function psy<T>(a: T[]): T[] {
a.length
return a;
}

psy<number>([1, 2, 3]);



function sort<T, U>(a: T, b: U): any[] {
let arr: any[] = [];
arr[0] = a;
arr[1] = b;
return arr;
}

sort<number, number>(1, 2);
sort<string, string>("a", "b");
sort<boolean, boolean>(true, false);

Guess you like

Origin blog.csdn.net/m0_74331185/article/details/130014200