typescript

原始数据类型包括:布尔值、数值、字符串以及 ES6 中的新类型Symbol和 ES10 中的新类型 BigInt

数组泛型

let list: Array<number> = [1, 2, 3];

 

任意类型

let list: any[] = ['itbaizhan', 10, {
website: 'https://xxx.com' }];

 

元组

let info: [string, number] = ['grb', 25]

 

使用元组的前提就是知道元素的数量和类型,这里顺序也是不能颠倒的

枚举

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}

 

联合类型

var age:number | string | boolean | [] = 20;

 

函数

TypeScript**定义函数**

function add(x:number, y:number):number {
    return x + y;
}

 

? 表示可选的参数

const add = (x:number, y:number,z?:number) =>
{
    return x + y
}
add(10,20)
add(10,20,30)

 

参数默认值

在 ES6 中,我们允许给函数的参数添加默认值,TypeScript 会将

添加了默认值的参数识别为可选参数

function info(name: string, age: number = 20)
{
    return name + age
}
info("grb")
info("grb",30)

 

ES6 中,可以使用 ...rest 的方式获取函数中的剩余参数(rest 参数)

function push(array:any[], ...items:any[]) {
    items.forEach(function(item) {
        array.push(item);
   });
    return array
}
let a: any[] = [];
const currentArray = push(a, 1, 2, 3);

 

重载

重载允许一个函数接受不同数量或类型的参数时,作出不同的处理

function reverse(x: number | string): number
| string | void {
    if (typeof x === 'number') {
        return
Number(x.toString().split('').reverse().join(
''));
   } else if (typeof x === 'string') {
        return
x.split('').reverse().join('');
   }
}

 

注解this的类型

function fancyDate(this:Date){
  return ${this.getDate()}/${this.getMonth()}/${this.getFullYear()}
}

 

生成器函数

function* createFibonacciGenerator() :IterableIterator<number>{
  let a=0
  let b=1
  while(true){
    yield a;
    [a,b]=[b,a+b]
  }
}

 

迭代器函数

let numbers={
  *[Symbol.iterator](){
    for(let n=1; n <=10 ;n++){
      yield n
    }
  }
}

 

public 任何地方都可访问

protected 可由当前类及其子类的实例访问

private 只可由当前类的实例访问

class Animal {
  move(distanceInMeters: number = 0) {
        console.log(`Animal moved
 ${distanceInMeters}m.`);
   }
 }
 class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
   }
 
 }
 const dog = new Dog();
 dog.bark();
 dog.move(10);

 

super

在子类的构造方法中调用super(),把父子关系连接起来

class Animal{
  public name:string;
  
 constructor(name:string){
  this.name = name;
   }
  move(distanceInMeters:number){
  console.log(`${this.name} moved
 ${distanceInMeters}m.`);
   }
 }
 class Dog extends Animal{
  constructor(name:string){
  super(name)
   }
  drak(){
  console.log(this.name + " Woof!Woof!")
   }
 }
 class Snake extends Animal{
   constructor(name:string){
  super(name)
   }
  move(distanceInMeters: number): void {
  console.log(this.name + ":---" +
 distanceInMeters)
 
  super.move(distanceInMeters)
  }
  }
 
  const d = new Dog("dog")
  d.move(100)
  d.drak()
 
  const s = new Snake("蛇")
  s.move(1000)

 

存取器

TypeScript 支持通过 getters/setters 来截取对对象成员的访问。

它能帮助你有效的控制对对象成员的访问。

1 TypeScript版本问题:增加 tsconfig.json ,并配置

2 编译时版本问题: tsc hello.ts -t es5

const fullNameMaxLength = 10;
class Person {
    constructor() {
        this._fullname = 'aaa';
    }
    get fullName() {
        return this._fullname;
    }
    set fullName(newName) {
        if (newName && newName.length > fullNameMaxLength) {
            throw new Error("fullname" + fullNameMaxLength);
        }
        this._fullname = newName;
    }
}
let p = new Person();
p.fullName = 'it';
if (p.fullName) {
    console.log(p.fullName)
}

 

使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用

实例方法

class Person{
  public name:string;
  constructor(name:string){
    this.name=name
  }
  sayhello(){
    console.log(`${this.name}`)
  }
}
const p=new Person("it")
p.sayhello()

 

静态方法

class Person{
  public name:string
  constructor(name:string){
    this.name=name
  }
  sayhello(){
    console.log(`${this.name}`)
  }
  static sayhi(){
    console.log("hi")
  }
}
Person.sayhi()

 

接口

function printLabel(label) {
    console.log(label.label);
}
var myobj = {
    label: "size 10 object"
};
printLabel(myobj);

 

接口可选属性(加上?👀

interface squareconfig{
  color?:string
  width?:number
}
function createsquare(config:squareconfig)
{
  let newSquare={
    color:'white',
    area:100
  }
  if(config.color){
    newSquare.color=config.color
  }
  if(config.width){
    newSquare.area=config.width
  }
  return newSquare
}
let mySquare=createsquare({ color: "black"
})
console.log(mySquare)

 

可选属性的好处之一是可以对可能存在的属性进行预定义,好处之

二是可以捕获引用了不存在的属性时的错误。 比如,我们故意将

createSquare 里的 color 属性名拼错,就会得到一个错误提示

接口只读属性

一些对象属性只能在对象刚刚创建的时候赋值。 你可以在属性名前

用 readonly 来指定只读属性

interface Point{
  readonly x:number
  readonly y:number
}
let p1:Point={x:10,y:20}
p1.x=5//error

 

readonly vs const👀

最简单判断该用 readonly 还是 const 的方法是看要把它做为变量使用

还是做为一个属性。 做为变量使用的话用 const ,若做为属性则使用 readonly

接口🐱‍🏍额外的属性检查

添加额外属性

interface squareconfig{
  color?:string
  width?:number
  [propName:string]:any
}
function createsquare(config:squareconfig)
{
  console.log(config)
}
let mySquare=createsquare({ colour: "red",
width: 100 })

 

接口**_** 函数类型😊

interface searchfunc{
  (source:string,subString:string)
}
let mysearch:searchfunc
mysearch=function(source:string,subString:string){
  console.log(source.substring)
}
mysearch("hello" ,"word")

 

接口_类类型

与传统面向对象里接口的基本作用一样,TypeScript 也能够用它来

明确的强制一个类去符合某种契约

interface searchfunc{
  (source:string,subString:string)
}
let mysearch:searchfunc
mysearch=function(source:string,subString:string){
  console.log(source.substring)
}
mysearch("hello" ,"word")

 

接口_继承接口

和类一样,接口也可以相互继承。 这让我们能够从一个接口里复制

成员到另一个接口里,可以更灵活地将接口分割到可重用的模块里

interface searchfunc{
  (source:string,subString:string)
}
let mysearch:searchfunc
mysearch=function(source:string,subString:string){
  console.log(source.substring)
}
mysearch("hello" ,"word")

 

 
 
posted @ 2023-07-27 15:24  guorunbin  阅读(7)  评论(0编辑  收藏  举报