当前位置:网站首页>TypeScript基础
TypeScript基础
2022-07-23 20:51:00 【阿波次嘚】
TS在js的基础上添加了很多java语言的特征
全局安装:
typescript: npm install -g typescript
执行ts文件: npm i -g ts-node
生成tsconfig.json配置文件:tsc -init
1. 用VSCode创建一个.ts文件
2. 强类型–为变量指定变量类型
var uname:string
uname = "1"
uname = null //no
uname = undefined //no
uname = 1 //no
uname = {
} //no
uname = [] //no
uname = function(){
} //no
var uname:string
uname = "1"
function a(uname:string){
//给形参显示指定类型
return uname.split("");
}
a('qwe')//自动监测参数类型是否匹配

3. ts文件在浏览器上无法运行,需要执行ts命令:tsc 01.tsts会检测【同时打开的】文件中 是否存在命名冲突
4. 基础数据类型
var a:null
a = null
var b:undefined
b = void 0
var c:string
c = 1+""
var d:number
d = Math.PI
d = Number.MAX_SAFE_INTEGER
d = 2 ** 24
var e:any //任意类型
e = {
}
e = []
var f: string | boolean //混合类型
f = `${
a}`
f = true
5. 数组类型
//规定数组元素类型 为 number
//基础写法-01
var TS_arr:Array<number> = [1,2,3,4,null,undefined]
//基础写法-02
var TS_arr:number[] = [1,2,3,4]
//多类型
var TS_arr:(number | string |null | undefined)[] = [1,2,3,4,null,undefined]
//数组对象写法 -01
var cc:{
a:number,b:string}[] = [
{
a:1,b:"aaac"},
{
a:3,b:"cccc"}
]
//数组对象写法 -02
type t = {
a:number,b:string}
var cc:t[] = [
{
a:1,b:"aaac"},
{
a:3,b:"cccc"}
]
//数组对象写法 -03
class t{
a:number
b:string
}
var cc:t[] = [
{
a:1,b:"aaac"},
{
a:3,b:"cccc"}
]
6. 接口
interface ts_json {
a:boolean,
b:string,
c?:number, // 加了问号代表 c属性可以不写
[propname:string]:any, //写任何属性 不被约束 (属性名是string类型 属性值是任何类型)
say():string, // 必须有say方法 而且返回值是string类型
}
//对对象字面量进行约束
var ts_json_01:ts_json = {
a:true,
b:"",
c:1,
d:true,
e:undefined,
say() {
return "返回值是接口中定义的string类型"
},
}
//对 类进行约束
class A implements ts_json{
a = true
b = ""
c = 1
say(){
return "返回值是接口中定义的string类型"
}
}
//接口继承
interface ts_son extends ts_json{
www() : string
}
class B implements ts_son{
a = true
b = ""
c = 1
say(){
return "返回值是接口中定义的string类型"
}
www(){
return "ts_son继承了 ts_json 所以这个类不仅得接受 ts_json接口的约束 还得添加一个 ts_son中约束的 www方法"
}
}
console.log(ts_json_01);
7. 对象类型
//接口约束对象
interface ts_json {
a:boolean,
b:string,
c?:number, // 加了问号代表 c属性可以不写
}
var ts_json_01:ts_json = {
a:true,
b:"",
}
console.log(ts_json_01);
//另一种写法
const aa: {
a:boolean,
b:string,
c:number,
} = {
a:true,
b:"",
c:123,
}
console.log(aa);
8. 类修饰符 publicprotectedprivate
class Limit{
public a=1 //实例化对象可用
protected b=2 // 类以及子类内部可用
private c=3 // 当前类内部可用
}
//ts定义一个类
const a :Limit = new Limit();
console.log(a.a)
9. 类型注解 类型推断
//类型注解:手动添加变量的类型
//类型推断:程序可以推断一部分变量的类型 所以可以不用特意添加
let a = 1;
a = "" //报错
10. 函数参数类型和返回类型检测
//有返回值写法
let a = 1;
function aa(b:number):number{
//防止类型意外变更
return b
}
aa(a)
//无返回值写法
function aa(b:number):void{
//防止代码中出现return语句 单写一个 return 不会出错
console.log(b+"")
return "";//报错
}
aa(a)
//执行死循环
let a = 1;
function aa(b:number):never{
//让函数一直执行
throw new Error()
}
function bb(b:number):never{
//让函数一直执行
while(true){
}
}
//参数是对象
function a({
aa}:{
aa:number}){
return aa
}
a({
aa:1})
11. 元组 解决数组类型与元素对应的顺序不同
//一维数组
const arr :[string,number] = ["",1]
//二维数组
const arr :[string,number][] = [
["",1],
["",1]
]
12. ts 类的 static getter setter
class A {
readonly b :string = "readonly关键字 设置属性只读"
constructor(private _a:string){
} //在构造函数内 定义一个 _a 属性 简化了定义属性的写法
get a(){
// getter
return this._a + "_get"
}
set a(val){
// setter
this._a = val + "_set"
}
static saw(){
//定义静态方法 直接通过类名 . 方法名调用 不用再实例化对象
console.log("saw方法")
}
}
let aa = new A("sss")
aa.a = "修改a__"
//aa.b = "修改b属性" //报错
console.log(aa.a)
//调用静态方法
A.saw()
13. ts 抽象类
//abstract 关键字定义抽象类 和 抽象方法
abstract class A{
abstract sss():any
}
class B extends A{
sss() {
console.log("B类需要定义 sss的方法体");
}
}
14. tsconfig.json 文件常用 配置 把注释解开即可
{
"include": ["01.ts"], //只编译 01.ts
"exclude": ["02.ts"], //编译除了 02.ts文件
"files": ["*.ts"],//编译 所有文件
"compilerOptions": {
"removeComments": true, //去掉注释 在执行的时候 直接终端输入 tsc即可
"strict": true, //开启严格模式
"noImplicitAny": true,//允许注释类型 为any 的 可以不用特意声明 any
"rootDir": "./src", //入口文件路径
"outDir": "./build", //出口文件路径
"sourceMap": true, //编译后 文件 和源文件的映射 方便排错
"noUnusedLocals": true, // 未使用的变量 不再进行打包
}
}
15. 联合类型 和 类型守护
interface AI {
a:string,
ai():any
}
interface BI {
b:string,
bi():any
}
//联合类型
interface AI {
a:string,
ai():string
}
interface BI {
b:string,
bi():string
}
function jw(j:AI | BI){
//联合类型
//类型守护 判断 属于哪个接口
let a = (j as AI).a;
console.log("a=>",a);
if(a){
let ai = (j as AI).ai;
console.log(ai());
}
let b = (j as BI).b;
console.log("b=>",b);
if(b){
let bi = (j as BI).bi;
console.log(bi());
}
}
jw({
a:"aaa",ai(){
return "调用了ai方法"}})
jw({
b:"bbb",bi(){
return "调用了bi方法"}})
16. 枚举类型
enum TYPE {
//定义枚举类型 默认从0开始 也可以像这样手动设置
A = 1,
B = 2,
C = 3,
}
//反查枚举属性
console.log("反查A=>", TYPE[1]);
function F(type: any) {
switch (type) {
case TYPE.A:
console.log("case_a");
break;
case TYPE.B:
console.log("case_b");
break;
case TYPE.C:
console.log("case_c");
break;
}
}
F(TYPE.B);
17. 泛型 它像一个参数一样 把一个类型做参数传递
//把类型做参数传递
//基本泛型 T代表泛型
function A<T>(a: T, b: T) {
console.log(a, b);
}
A<string>("1", "2");
A<number>(1, 2);
//定义多个泛型
function D<T, P>(a: T, b: P) {
console.log(a, b);
}
D<string, number>("1", 1);
//数组泛型 T代表泛型
function B<T>(a: Array<T>) {
console.log(a);
}
B<number>([1, 2]);
//类泛型
class AA<T> {
constructor(private a: T) {
}
say_a(): T {
return this.a;
}
}
let a = new AA<string>("AA传入的参数");
console.log(a.say_a());
//泛型继承 约定里面必须有一些东西
interface J {
name: string;
}
function JC<T extends J>(jc: T) {
console.log(jc);
}
JC({
name: "1" }); // J 中 要求必须有一个 name属性
//泛型约束
function YS<T extends string | number>(jc: T) {
//泛型只能 从类型 string 和 number中 选择
console.log(jc);
}
YS("ys参数");
18. 命名空间 用命名空间将代码包裹 防止代码全局污染 实现模块化 命名空间可以嵌套
//定义命名空间
namespace N {
class A {
constructor(public a: string) {
console.log(a);
}
}
class B {
constructor(public b: string) {
console.log(b);
}
}
class C {
constructor(public c: string) {
console.log(c);
}
}
//如果你想在外界使用 需要 export 暴露出去
export class Main {
constructor() {
new A("aaaa");
new B("bbbb");
new C("cccc");
}
}
}
let m = new N.Main();
技术参考 b站:【技术胖】TypeScript从入门到精通视频教程-2020年新版
写博客这么长时间 发现博客除了可以整理 我们不经常用但是很重要的容易忘的知识点 ,更重要的是学习能力得到了很大的提升, 坚持了这么久 我依然觉得写博客从来不只是在做一两件事, 而是把你的综合能力提升到了一定的高度 ,个人认为这就是学习的最好的方式。
边栏推荐
猜你喜欢

Choice is greater than effort! Guiyang campus Xiaoge 0 foundation successfully transferred to software testing and gained 12K!

MySQL(3)

使用TinkerPop框架对GDB增删改查

深入浅出边缘云 | 1. 概述

对接湖南CA使用U_KEY登录

高数下|三重积分的计算2|高数叔|手写笔记

Mysql的前世今生,Hello,Mysql

The instructions on Microsoft website about opening or closing smartscreen in edge browser are incorrect

Interpretation of Flink catalog

Himawari-8 data introduction and download method
随机推荐
Jetson nano recording stepping on the pit (it will definitely solve your problem)
第十二天:续第十一天(BGP相关知识)
美团大脑百亿级知识图谱的构建及应用进展
Kubevela offline installation
支付产品及其使用场景
The instructions on Microsoft website about opening or closing smartscreen in edge browser are incorrect
[force buckle] the sum of the nearest three numbers
OpenLayers实例-Advanced Mapbox Vector Tiles-高级Mapbox矢量贴图
CDR插件开发之Addon插件003 - 认识解决方案(sln)和项目(csproj)文件
[cloud co creation] what magical features have you encountered when writing SQL every day?
jsp+ssm+mysql实现的租车车辆管理系统汽车租赁
Improving Performance with Explicit Rendering(通过显式渲染提高性能)
现在完全不知道怎么同步
If the order is not paid within 30 minutes, it will be automatically cancelled
TROPOMI(哨兵5P)数据介绍及下载方法
Tropomi (sentinel 5p) data introduction and download method
网上开通证券账户安全吗?
Today's sleep quality record 81 points
LeetCode热题 HOT52-100
Choice is greater than effort! Guiyang campus Xiaoge 0 foundation successfully transferred to software testing and gained 12K!