Geek

博客园 首页 新随笔 联系 订阅 管理

ts基础类型

let s = 'st';
console.log(s);

let arr: Array<number | string> = [1, 2, 3, '4'];

let tupe: [number, string] = [0, '1'];
//
// 函数类型
// 对象

let obj: object = { x: 1 };
// symbol类型
let sym: symbol = Symbol();


枚举类型优化代码判断

枚举类主要用来定义一些常量,比如请求URL、文本提示信息、分类信息等等,这样方便记忆,减少硬编码,增加可读性。


enum Role {
  Reporter = 1,
  Developer,
  Maintainer,
  Owner,
  Guest,
}
console.log(Role,Role.Owner)

const enum RoleEnum{
    Reporter = 1,
    Developer,
    Maintainer,
    Owner,
    Guest
}

function initByRole(role: RoleEnum) {
    if (role === RoleEnum.Reporter || role === RoleEnum.Developer) {
        // do sth
    } else if (role === RoleEnum.Maintainer || role === RoleEnum.Owner) {
        // do sth
    } else if (role === RoleEnum.Guest) {
        // do sth
    } else {
        // do sth
    }
}

声明数组

// 字符串数组
interface StringArray {
  [index: number]: String
}
let shs :StringArray = ['a','b']




定义函数类型接口

// case1
let add: (x: number, y: number) => number;
// case2
interface Add {
  (x: number, y: number): number;
}
// case3
type AddFun = (x: number, y: number) => number;

var fn :AddFun = (a: number, b: number) => a + b;


函数重载

// 混合接口
//  允许实现函数重载
function add(...rest: number[]): number;
function add(...rest: string[]): string;
function add(...rest: any[]): any {
  var typ = typeof rest[0]
  if (typ === 'string') {
    return rest.join('')
  } else if (typ == 'number') {
    return rest.reduce((pre,cur) => pre+cur)
  }
}

console.log(add('x','y','z'),add(1,2,3))


class 使用方法

class Dog {
  constructor(name: string) {
    this.name = name;
    // this.pri = 'x'
  }
  public name: string;
  // private pri: string;
  run() {}
}
console.log(Dog.prototype);
console.log(new Dog('wangwang'));
// output:
// {}
// Dog{name:'wangwang' }

// 类继承
class husky extends Dog {
  constructor(name: string,color:string) {
    super(name)
    this.color = color
  }
  color: string
}


类和接口关系

posted on 2023-02-09 12:00  .geek  阅读(26)  评论(0编辑  收藏  举报