TypeScript : 环境安装及使用

2019-05-20  本文已影响0人  _凌浩雨
1). TypeScript官网
2). Node
npm --verison
# 设置镜像源
npm config set registry https://registry.npm.taobao.org --global
npm config set disturl https://npm.taobao.org/dist --global
npm install -g typescript
tsc filename.ts

3). 语法特性
4). 使用
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="index.js"></script>
    </head>
    <body>
    </body>
</html>
alert('Hello world in TypeScript!');
tsc index.ts

运行改命令后再ts文件同级目录生成index.js文件

效果.png
5). 类型批注
function area(shape: string, width: number, height: number): string {
    var area = width * height;
    return "I am a " + shape + " with an area of " + area + " cm squred";
}

document.write(area('rectangle', 30, 15));
6). 接口
interface Shape {
    name: string,
    width: number,
    height: number,
    color?: string
}

function area(shape: Shape): string {
    var area = shape.width * shape.height;
    return "I am a " + shape.name + " with an area of " + area + " cm squred";
}

document.write(area({name: 'rectangle', width: 30, height: 15}));
7). 箭头函数表达式(lambda表达式)
var shape = {
    name: 'rectangle',
    popup: function () {
        console.log('This inside popup: ' + this.name);
        
        setTimeout(() => {
            console.log('This inside setTimeout(): ' + this.name);
            console.log("I am a " + this.name);
        }, 3000);
    }
}

shape.popup();
8). 类
class Shape {
  area: number;
  // 私有化
  private color: string;
  // name 公有化
  constructor(public name: string, width: number, height: number) {
    this.area = width * height;
    this.color = "pink";
  }

  shoutout() {
    return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
  }
}

var square = new Shape("square", 30, 30);

console.log(square.shoutout);
console.log('Area of Shape: ' + square.area);
console.log('Name of Shape: ' + square.name);
console.log('Color of Shape: ' + square.color); // 未定义
console.log('Width of Shape: ' + square.width); // 未定义
console.log('Height of Shape: ' + square.height); // 未定义
9). 继承
class Shape {
  area: number;
  // 私有化
  private color: string;
  // name 公有化
  constructor(public name: string, width: number, height: number) {
    this.area = width * height;
    this.color = "pink";
  }

  shoutout() {
    return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
  }
}

class Shape3D extends Shape {
  volume: number;
  constructor(public name: string, width: number, height: number, length: number) {
    super(name, width, height);
    this.volume = length * this.area;
  }

  shoutout() {
    return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
  }

  superShout() {
    return super.shoutout();
  }
}

var cube = new Shape3D("cube", 30, 30, 30);
console.log(cube.shoutout());
console.log(cube.superShout());
上一篇下一篇

猜你喜欢

热点阅读