深入理解TypeScript——第一章:上手篇

424 阅读3分钟

       怎么定义TypeScript呢? TypeScript是一个工具,是一个编译器。

       ts确实有很多好处,但是也有很多弊端,js根深蒂固,浏览器都是对照js去适配运行环境、调试等等,没办法用ts直接替换掉,而js又太“动态”了,微软才出了个这个。        我看了ts的tsc.js文件,大致看了下,mircosoft的ts主要是通过nodejs执行tsc.js,用了很多插件做处理,将.ts文件做解析,通过各种标记、解析、逻辑处理,编译成浏览器可用的js文件。具体的可以把官方文件download下来,运行就好了,代码量很大,慎重慎重!

一、编译代码

       TypeScript,通过它的能力,默认使用tsc命令,可以根据.ts为后缀名的文件生成一个新的js文件。

二、类型注解

       TypeScript里的类型注解是一种轻量级的为函数或变量添加约束的方式。TypeScript提供了静态的代码分析,它可以分析代码结构和提供的类型注解。

function doSth(who: string): string {
  return "I want to say hello to " + who;
}

let who = 'her';

const doWhat = doSth(who);

console.log('doWhat:', doWhat)
// doWhat: I want say hello to her

       这里插个题外话,如果部分语法产生error的话,要考虑tsconfig.json这样的配置文件(比如lib部分)是否支持了你需要的Javascript规范,如果不支持的话,建议使用polyfill。

三、接口

       允许我们在实现接口时候只要保证包含了接口要求的结构就可以。

interface Girl {
  hair: string;
  face: string;
}

function describe(girl: Girl): string {
  let words = 'she has '
  let decs = Object.entries(girl)
  let len = decs.length

  for (let i = 0; i < len; i++) {
    const [where, like] = decs[i];
    words+=(like + ' ' + where)
    words+=(i === len - 1 ? '' : ' and ')
  }
  return words
}

const sentence = describe({
  hair: 'long',
  face: 'beautiful'
})

console.log('sentence:', sentence);
// sentence: she has long hair and beautiful face

四、类

      支持基于类的面向对象编程。
在构造函数的参数上使用public等同于创建了同名的成员变量。

class She {
  praise: string;
  constructor(public hair: string, public face: string) {
    // this.praise =  hair + ' hair' + " and " + face + ' face';
  }
}

interface Girl {
  hair: string;
  face: string;
}

function describe(girl: Girl): string {
  let words = 'she has '
  let decs = Object.entries(girl)
  let len = decs.length

  for (let i = 0; i < len; i++) {
    const [where, like] = decs[i];
    words+=(like + ' ' + where)
    words+=(i === len - 1 ? '' : ' and ')
  }
  return words
}

const she = new She('long', 'beautiful')

const sentence = describe(she)

console.log('sentence', sentence);

       上面这段代码通过ts编译,成为了下面这段代码。

var She = /** @class */ (function () {
    function She(hair, face) {
        this.hair = hair;
        this.face = face;
        // this.praise =  hair + ' hair' + " and " + face + ' face';
    }
    return She;
}());
function describe(girl) {
    var words = 'she has ';
    var decs = Object.entries(girl);
    var len = decs.length;
    for (var i = 0; i < len; i++) {
        var _a = decs[i], where = _a[0], like = _a[1];
        words += (like + ' ' + where);
        words += (i === len - 1 ? '' : ' and ');
    }
    return words;
}
var she = new She('long', 'beautiful');
var sentence = describe(she);
console.log('sentence', sentence);

       看起来,只是多了一些特殊的注释,以及修改了一些局部变量名,所以ts主要的功能其实是为了规范书写,校验传入参数是否正确,从而实现更高质量的代码!