ts各种类型和用法

编程语言的类型

动态类型语言

静态类型语言

typescript

特性

优势

类型注解 & 类型推断

基础类型 & 对象类型

联合类型

交叉类型

Partial

枚举

函数注解

数组注解

interface & type

类型断言

泛型

泛型约束

声明文件

typescript编译

ts-node 编译执行.ts 文件

tsc

tsconfig

typescript + React

编程语言的类型

动态类型语言

运行期间做数据类型检查 js ruby python

静态类型语言

编译期间类型检查 c c++ java

typescript

==冒号后面的都是类型==

特性

typescript 是 js 的超集

拥有静态类型

需要编译成 js 运行

优势

ts 的静态类型可以在开发过程中,发现潜在问题

更好的编辑器提示

通过静态类型的声明,代码清晰易读

// js中变量是动态类型 可以随时改变类型leta=1;a='str'// ts中是静态类型 改变类型会报错letb=1;b='str'

类型注解 & 类型推断

ts 自动启用类型推断,判断变量类型 如果能分析变量类型不需要类型注解,否则需要

基础类型 & 对象类型

// 基础类型 string number boolean symbol void null undefinedletcount: number;// 对象类型 {} [] function Classconstteacher: {name: string;  age: number;} = {name:'jason',age:28,};constnumbers: number[] = [1,2,3];classPerson{}constp: Person =newPerson();constgetTotal:()=>number =()=>{return123;};

联合类型

letmyName:string| number;

交叉类型

将多个类型合并成一个类型

typeNativeButtonProps = BaseButtonProps & ButtonHTMLAttributestypeAnchorButtonProps = BaseButtonProps & AnchorHTMLAttributes

Partial

把一些属性变为可选的

exporttypeButtonProps = Partial

枚举

enum TabTypes {Case='case',  Ganged ='ganged',}const[currentTab, setCurrentTab] = useState(TabTypes.Case);if(currentTab === TabTypes.Case) {        setCaseSource(insertKeys(res.data));      }else{        setGangedSource(insertKeys(res.data));}

函数注解

函数的入参需要类型注解,返回值如果可以类型推断的话不需要写

// 函数入参及返回值注解 c:可选参数只能放最后functionadd(a: number, b: number, c?: number):number{returna + b;}// 函数表达式constadd2:(x: number, y: number) =>number=(a,b)=>{returna+b}// interface写法interface IFn {  (x: number,y: number): number;}constadd2: IFn =(a, b) =>{returna + b;};// type写法type fn =(x: number, y: number) =>number;constadd2: fn =(a, b) =>{returna + b;};// 函数解构的写法functionadd2({ a, b }:{a:number, b: number}):number{returna + b;}add2({a:1,b:2});consttotal = add(1,2);// 无返回值functionsayHello():void{console.log('hello');}// 函数永远不会执行完functionerrorEmitter():never{thrownewError('error');console.log('end');}

数组注解

// 数组注解 能推断出来的不需要注解 直接的赋值的数组ts可以类型推断出来constarr1: number[] = [1,2,3];// 只能是numberconstarr2: (number |string)[] = ['1',2,3];// 可以是number或stringconstarr3: undefined[] = [undefined, undefined];// 只能是undefined// 对象数组constarr4: { name:string; age: number }[] = [{ name:'a', age:18}];// 类型别名 对上面的另一种写法type User = { name:string; age: number };constarr5: User[] = [{ name:'a', age:18}];// 元组 tuple 一个数组的长度固定 元素顺序类型固定constinfo: [string,string, number] = ['andy','male',20];

interface & type

interface是数据的共性的抽象 有自己的属性 只是在开发过程中做语法提示校验的工具 编译后不存在

对对象的形状(shape)的描述

interfacePerson{readonlyname:string;// 只读 该属性再写会报错age?: number;// 可选属性 可有可无[propName: string]: any;// 将来多出的其他属性string类型也是可以的say?():string;// 方法属性 返回值stringsay: ()=>{}}// 接口继承interfaceTeacherextendsPerson{    teach():string;// 自己的属性}

定义函数

// interface 定义函数类型interfaceISayHi{ (word:string):string;}constsay: SayHi = () => {return'hi';};interfaceIModalProps{  visible: boolean;// 是否可见handleClose: () =>void;// 隐藏自身form: any;}

对类(class)进行抽象

interfaceRadio{  switchRadio():void}interfaceBatteryextendsRadio{  checkBatter():void}// 类实现interfaceclassCarimplementsRadio{  switchRadio() {  }}classPhoneimplementsBattery{  switchRadio() {  }  checkBatter() {  } }

type 类型别名 只是简单的别名

// 常用于type fnType =(a: string) =>stringtype FooType = string | fnTypetype Person = {name: string;  age?: number;  };functiongetName(person: Person):void{console.log(person.name);}constsetName =(person: Person, newName: string) =>{  person.name = newName;returnperson;};// 传对象引用和对象字面量的校验结果不一样 前一种无强校验letp = {name:'andy',sex:'male', say() {} };getName(p);getName({name:'andy',sex:'male'});setName({name:'jason'},'andy');

类型断言

联合类型时 ts 只拿到公有的一些方法 使用类型断言联合类型的某一种类型

functiongetLength(input: string | number){// 这里会报错if(input.length){returninput.length  }}functiongetLength(input: string | number){// 类型断言 告诉ts我知道他是什么类型conststr = inputasStringif(str.length){returnstr.length  }}functiongetLength(input: string | number){// 另一种写法if((input).length){      return (input).length  }}

ts 给 es6 的类增加了访问修饰符

classPerson{/**

  *  public 允许在类的内外调用

  *  private 允许类内不允许子类

  *  protected 允许类内及继承的子类

  *  readonly 只能读不能写

  * */// 简写constructor(private_name:string,publicage: number){}// 常规写法// public name: string;// constructor(name) {//  this.name = name;// }// getter 属性getname(){returnthis._name +'geted';  }// setter 属性setname(value:string){this._name =value}}constp =newPerson('nn',18);console.log(p.name);p.name ='change';console.log(p.name);// ts 实现单例模式classDemo{// 私有静态属性privatestaticinstance: Demo;// 私有constructorprivateconstructor(publicname:string){};// 公共静态方法staticgetInstance(){if(!this.instance){this.instance =newDemo('lee')        }returnthis.instance    }}// 调用的是同一个instanceconstdemo1 = Demo.getInstance();constdemo2 = Demo.getInstance();console.log(demo1, demo2)

泛型

泛型,泛指的类型, 定义==函数、接口和类==时使用占位符不指定具体类型,使用时才指定,用<>先声明, 声明泛型 T 可以任意命名函数泛型,代表不知道什么类型的同一种类型

函数泛型

// 常规写法functionplus(a: number, b):number{returna + b;  }consta = plus// interface写法interface IPlus{    (a: number,b: number): number}constplus:IPlus=(a,b)=>{returna + b;}consta = plus(2,2)// 泛型写法functionjoin(first: T, second: T):T{return`${first}${second}`;}// 可以声明 也可以类型推断join(1,1);join(1,2);functionjoin(first: T, second: P){return`${first}${second}`;}

接口泛型

interface IPlus {  (a: T,b: T): T;}constplus: IPlus =(a, b) =>{returna + b;};consta = plus(1,2);constconnet: IPlus =(a, b) =>{returna + b;};constb = connet('hello','ts');

类泛型

classQueue{    private data=[]    push(item: T){returnthis.data.push(item)    }    pop(): T{returnthis.data.pop()    }}constq1=newQueue()q1.push(1)q1.push(2)console.log(q1.pop().toFixed());constq2=newQueue()q2.push('ss')console.log(q2.pop().trim())

泛型约束

// 泛型约束 使用extends使泛型满足某些条件interfaceIWithLength{    length: number}functionecho(args: T):T{// 需要一个有length属性的泛型console.log(args.length);returnargs  }constres =echo('sss')constres2=echo([1,2,3])// 泛型继承 使用extends扩展类型interfaceIJoin{    name: string;}functionjoin(data:T[]){returndata[0].name;}join([{ name:'sss'}]);

声明文件

第三方库使用时需要声明文件 声明文件以.d.ts 结尾 如:jQuery.d.ts 有了声明文件后项目中就可以使用 jQuery() 提供语法提示且不报错

搜索第三方库的声明文件 TypeSearch 从 npm 安装第三方库的声明文件 npm @types

// jQuery.d.tsdeclarevarjQuery: (selector:string) =>any;

typescript编译

ts-node 编译执行.ts 文件

npminstall -g ts-nodets-node script.ts

tsc

不带任何输入文件的情况下调用 tsc,编译器会从当前目录开始去查找 tsconfig.json 文件,逐级向上搜索父目录。

不带任何输入文件的情况下调用 tsc,且使用命令行参数--project(或-p)指定一个包含 tsconfig.json 文件的目录。

当命令行上指定了输入文件时,tsconfig.json 文件会被忽略。

tsconfig

生成tsconfig.json

tsc--init

使用指定的tsconfig.json编译

// pacage.json"script":{"build-ts":"tsc -p tsconfig.build.json"}


typescript + React

常规写法

importReactfrom'react';interface IHelloProps {name: string}constHello =(props: IHelloProps) =>{return

{`Hello ${props.name}`}

;};exportdefaultHello;

使用 react 提供的声明 /node_modules/@types/react/index.d.ts 声明文件

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容