ts中基本數據類型(上)


 

 

/* 定義數組*/
var arr: number[] = [1, 2, 3];
var arr1: Array<number> = [1, 2, 3];
var arr2: [string, number] = ['this is string', 1];
/* 枚舉類型*/
enum Status {
  success = 200,
  error = 404
}
let statu: Status = Status.success; // 200
let statu2: Status = Status.error; // 404
/*
enum Color {
  blue,
  red,
  yellow
}
let blueIndex:Color = Color.blue; // 0
let redIndex:Color = Color.red; // 1
*/
enum Color {
  blue,
  red = 4,
  yellow
}
let blueIndex: Color = Color.blue;
console.log(blueIndex)
let redIndex: Color = Color.red;
console.log(redIndex) // 4
let yellowIndex: Color = Color.yellow;
console.log(yellowIndex) //5

 

/* void類型 */

 

function run(): void {
  console.log("I am runing")
}

 

function isNumber(): number {
  return 124;
}

 

/* 函數類型 */
// es5中的函數類型
function eat() {
  return 'eating';
}
var eat2 = function () {
  return 'eating'
}

 

// ts中的函數類型
function eat3(): string {
  return 'eating';
}
// 定義傳參數類型
function eat4(name: string, many: number): string {
  return `我吃飽了${name}`;
}
// 默認參數

 

function eat5(name: string, many: number = 4): string {
  return `我吃飽了${name}`;
}
// 三點運算符
function sum(...result: number[]) {
  let sum;
  for (let index = 0; index < result.length; index++) {
    sum += result[index];
  }
  return sum;
}
sum(1,2,3); // 6
 
 
/* es5中對象的繼承 */
/*
 
function Person() {
  this.name ='fasd';
  this.age = 4;
  this.worker = function() {
  console.log('工作');
  }
}

 

function Web() {
  Person.call(this); // 對象冒充繼承法(只能繼承對象屬性和方法不能繼承原型鏈上屬性和方法)
}



var w = new Web();
w.worker();
*/
function Person(name,age) {
  this.name =name;
  this.age = age;
  this.worker = function() {
  console.log('工作');
  }
}

 

function Web(name,age) {
  Person.call(this,name,age);
}

 

Web.prototype = Person.prototype; // Web.prototype = new Person();
var w = new Web('fsdf', 34);
w.worker();
/* 類的繼承 */

 

class animal {
  name:string;
  constructor( name) {
  }
  look() {
    console.log('看世界')
  }
}

 

class Person2 extends animal{
  name: string;
  age: number;
  constructor(name,age) {
    super(name)
  this.name = name;
  this.age = age;
  }
  eat () {
    console.log(`我吃${this.age}個蛋`)
  }
}
var p = new Person2('df', 22);
alert(p.look()) // 看世界


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM