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()) // 看世界