TypeScript

1、继承

  1. function add(x:number,z?:number):number{}
  2. // 可索引类型
  3. interface RandomMap {
  4. [propName: string]: string;
  5. }
  6. const test:RandomMap{
  7. a:'1',
  8. b:'2'
  9. }
  10. // 类数组
  11. interface LikeArray {
  12. [index: number]: string;
  13. }
  14. const likeArray:LikeArray=['1','2','3']
  15. //函数添加属性
  16. interface FunctionWithProps {
  17. (x: number): number;
  18. name: string;
  19. }
  20. const a:FunctionWithProps=(x:number)=>{
  21. return x
  22. }
  23. a.name='abc'
  24. class Animal {
  25. //修饰符
  26. private|public|protected name: string
  27. constructor(name: string) {
  28. this.name = name
  29. }
  30. run() {
  31. return `${this.name} is running`
  32. }
  33. }
  34. const snake = new Animal('haha')
  35. snake.run()
  36. //继承
  37. class Dog extends Animal {
  38. //多态
  39. bark() {
  40. return `${this.name} is bark`
  41. }
  42. }

2、实现

  1. interface ClockInterface {
  2. currentTime: number
  3. alter(): void
  4. }
  5. interface GameInterface {
  6. play: void
  7. }
  8. interface ClockStatic {
  9. //构造函数
  10. new (h: number, m: number): void
  11. //静态属性
  12. time: number
  13. }
  14. //实现接口
  15. const Clocl: ClockStatic = class Clock implements ClockInterface {
  16. constructor(h: number, m: number) {}
  17. static time: 10
  18. currentTime: number
  19. alter(): void {
  20. throw new Error('Method not implemented.')
  21. }
  22. }
  23. //实现多接口
  24. class CellPhone implements ClockInterface, GameInterface {
  25. play: void
  26. currentTime: number
  27. alter(): void {
  28. throw new Error('Method not implemented.')
  29. }
  30. }

3、泛型

  1. //如果是string,返回就有string的特性
  2. //如果是number,返回就有number的特性
  3. function echo<T>(arg: T): T {
  4. return arg
  5. }
  6. const res: number = echo(12)
  7. function swap<T, U>(tuple: [T, U]): [U, T] {
  8. return [tuple[1], tuple[0]]
  9. }
  10. const res1 = swap(['string', 123])
  11. interface GithubResp {
  12. name: string
  13. count: number
  14. }
  15. function withApi<T>(url: string): Promise<T> {
  16. return fetch(url).then(res => res.json())
  17. }
  18. withApi<GithubResp>('github.user').then(res => {
  19. res.count
  20. })

4、高级特性

  1. type PersionResp = {
  2. name: string
  3. count: number
  4. }
  5. //相当于PersionResp的联合类型 获得type属性的键
  6. type Keys = keyof PersionResp
  7. //获得定义type属性的值
  8. type nameType = PersionResp['name']
  9. //?可选类型 p in Keys 遍历keys
  10. type Test = { [p in Keys]?: PersionResp[p] }
  11. //结果:
  12. // type Test = {
  13. // name?: string
  14. // count?: number
  15. // }
  16. const str2 = '124' //因为const是常量,所以类型是124
  17. let str1 = '123' //是变量 类型是string
  18. function sum(a: number, b: number): number {
  19. return a + b
  20. }
  21. //类型别名
  22. type PlusType = (x: number, y: number) => number
  23. let sum2: PlusType
  24. sum2(1, 2)
  25. interface IName {
  26. name: string
  27. }
  28. type TPerson = IName & { age: number }
  29. let person: TPerson = {
  30. name: '1',
  31. age: 1
  32. }
  33. //联合类型
  34. let numberOrString: number | string
  35. function getLength(input: number | string) {
  36. //类型断言
  37. const str = input as string
  38. if (str.length) {
  39. return str.length
  40. } else {
  41. const num = input as number
  42. return num.toString().length
  43. }
  44. }
  45. interface IWithLength {
  46. length: number
  47. }
  48. //extends T中必须包含IWithLength的属性,这样就支持输出length,包括number、boolean
  49. function echoWith<T extends IWithLength>(arg: T): T {
  50. console.log(arg.length)
  51. return arg
  52. }
  53. const arr = echoWith([1, 2, 3])
  54. const str = echoWith('123')
  55. const obj = echoWith({ length: 1, width: 12 })
  56. type NonType<T> = T extends null | undefined ? never : T
  57. let demo1: NonType<number> //类型是T
  58. let demo2: NonType<null> //类型是never

image.png
源码分析
image.png
image.png

声明文件

  1. jQuery('#id')
  2. //如果没有声明文件,会直接报错,针对一些第三包不支持ts的情况,可以写声明文件,默认全局使用
  1. declare var jQuery: (selector: string) => any

举例:

  1. function myFetch(url, method, data) {
  2. return fetch(url, {
  3. body: data ? JSON.stringify(data) : '',
  4. method
  5. }).then(res => res.json())
  6. }
  7. myFetch.get = (url, data) => {
  8. return myFetch(url, 'get', data)
  9. }
  10. myFetch.post = (url, data) => {
  11. return myFetch(url, 'post', data)
  12. }
  13. export default myFetch
  1. type HttpMethod = 'GET' | 'POST' | 'DELETE' | 'PATCH'
  2. declare function myFetch<T = any>(url: string, method: HttpMethod, data?: any): Promise<T>
  3. //namespace 里面是定义的方法
  4. declare namespace myFetch {
  5. const get: <T=any>(url: string, data?: any) => Promise<T>
  6. const post: <T=any>(url: string, data?: any) => Promise<T>
  7. }
  8. //导出 可以作为第三方插件使用
  9. export = myFetch

注意:需要将ts、d.ts放在@types,作为第三方插件使用,否则使用泛型会报错

  1. //res 类型是any
  2. myFetch('test', 'GET', { name: 'hello' }).then(res => {})
  3. //res number
  4. myFetch<number>('test', 'GET', { name: 'hello' }).then(res => {})
  5. //any
  6. myFetch.get('test', 'data').then(res => {})

image.png

  1. type CopyActionOptions = {
  2. container?: Element
  3. }
  4. type Response = 'success' | 'error'
  5. declare class ClipboardJS {
  6. constructor(selector: string, options: ClipboardJS.Options)
  7. on(type: Response, handler: (e: ClipboardJS.Event) => void): this
  8. destory(): void
  9. }
  10. declare namespace ClipboardJS {
  11. interface Options {
  12. action?(elem: Element): Action
  13. target?(elem: Element): Element
  14. text?(elem: Element): string
  15. container?: Element
  16. }
  17. }
  18. export = ClipboardJS