TypeScript
1、继承
function add(x:number,z?:number):number{}// 可索引类型interface RandomMap {[propName: string]: string;}const test:RandomMap{a:'1',b:'2'}// 类数组interface LikeArray {[index: number]: string;}const likeArray:LikeArray=['1','2','3']//函数添加属性interface FunctionWithProps {(x: number): number;name: string;}const a:FunctionWithProps=(x:number)=>{return x}a.name='abc'class Animal {//修饰符private|public|protected name: stringconstructor(name: string) {this.name = name}run() {return `${this.name} is running`}}const snake = new Animal('haha')snake.run()//继承class Dog extends Animal {//多态bark() {return `${this.name} is bark`}}
2、实现
interface ClockInterface {currentTime: numberalter(): void}interface GameInterface {play: void}interface ClockStatic {//构造函数new (h: number, m: number): void//静态属性time: number}//实现接口const Clocl: ClockStatic = class Clock implements ClockInterface {constructor(h: number, m: number) {}static time: 10currentTime: numberalter(): void {throw new Error('Method not implemented.')}}//实现多接口class CellPhone implements ClockInterface, GameInterface {play: voidcurrentTime: numberalter(): void {throw new Error('Method not implemented.')}}
3、泛型
//如果是string,返回就有string的特性//如果是number,返回就有number的特性function echo<T>(arg: T): T {return arg}const res: number = echo(12)function swap<T, U>(tuple: [T, U]): [U, T] {return [tuple[1], tuple[0]]}const res1 = swap(['string', 123])interface GithubResp {name: stringcount: number}function withApi<T>(url: string): Promise<T> {return fetch(url).then(res => res.json())}withApi<GithubResp>('github.user').then(res => {res.count})
4、高级特性
type PersionResp = {name: stringcount: number}//相当于PersionResp的联合类型 获得type属性的键type Keys = keyof PersionResp//获得定义type属性的值type nameType = PersionResp['name']//?可选类型 p in Keys 遍历keystype Test = { [p in Keys]?: PersionResp[p] }//结果:// type Test = {// name?: string// count?: number// }const str2 = '124' //因为const是常量,所以类型是124let str1 = '123' //是变量 类型是stringfunction sum(a: number, b: number): number {return a + b}//类型别名type PlusType = (x: number, y: number) => numberlet sum2: PlusTypesum2(1, 2)interface IName {name: string}type TPerson = IName & { age: number }let person: TPerson = {name: '1',age: 1}//联合类型let numberOrString: number | stringfunction getLength(input: number | string) {//类型断言const str = input as stringif (str.length) {return str.length} else {const num = input as numberreturn num.toString().length}}interface IWithLength {length: number}//extends T中必须包含IWithLength的属性,这样就支持输出length,包括number、booleanfunction echoWith<T extends IWithLength>(arg: T): T {console.log(arg.length)return arg}const arr = echoWith([1, 2, 3])const str = echoWith('123')const obj = echoWith({ length: 1, width: 12 })type NonType<T> = T extends null | undefined ? never : Tlet demo1: NonType<number> //类型是Tlet demo2: NonType<null> //类型是never
声明文件
jQuery('#id')//如果没有声明文件,会直接报错,针对一些第三包不支持ts的情况,可以写声明文件,默认全局使用
declare var jQuery: (selector: string) => any
举例:
function myFetch(url, method, data) {return fetch(url, {body: data ? JSON.stringify(data) : '',method}).then(res => res.json())}myFetch.get = (url, data) => {return myFetch(url, 'get', data)}myFetch.post = (url, data) => {return myFetch(url, 'post', data)}export default myFetch
type HttpMethod = 'GET' | 'POST' | 'DELETE' | 'PATCH'declare function myFetch<T = any>(url: string, method: HttpMethod, data?: any): Promise<T>//namespace 里面是定义的方法declare namespace myFetch {const get: <T=any>(url: string, data?: any) => Promise<T>const post: <T=any>(url: string, data?: any) => Promise<T>}//导出 可以作为第三方插件使用export = myFetch
注意:需要将ts、d.ts放在@types,作为第三方插件使用,否则使用泛型会报错
//res 类型是anymyFetch('test', 'GET', { name: 'hello' }).then(res => {})//res numbermyFetch<number>('test', 'GET', { name: 'hello' }).then(res => {})//anymyFetch.get('test', 'data').then(res => {})

type CopyActionOptions = {container?: Element}type Response = 'success' | 'error'declare class ClipboardJS {constructor(selector: string, options: ClipboardJS.Options)on(type: Response, handler: (e: ClipboardJS.Event) => void): thisdestory(): void}declare namespace ClipboardJS {interface Options {action?(elem: Element): Actiontarget?(elem: Element): Elementtext?(elem: Element): stringcontainer?: Element}}export = ClipboardJS


