七天学习TypeScript(一)

716 阅读2分钟
一、引言

  上帝七天可以创世纪,我们七天学习TypeScript应该不是什么难事。学习一门语言的语法并不难,熟悉和精通则需要很多年的实践和沉淀。有幸参加了大崔哥的对赌学习,正好这几天可以系统学习一下。崔老师安排的是4天的对赌学习计划,我想给自己多3天的时间运用学到的知识自己写一个小例子,作为实践成果。这几天我的时间基本上是这样安排的:大概每天4-5个小时,1.5个小时看崔老师直播;1.5个小时自学复习;1.5个小时写文章总结。有道是:“学而不思则罔,思而不学则殆”,下面正式开始。

二、正文

参考网址:www.typescriptlang.org

废话不多说,第一天的基础知识如下。

1、引出TypeScript的必要性---静态类型检查,可以在运行前(编译时甚至编辑时)就进行语法检查,把bug消灭在萌芽状态。

  • 例子1,调用了toLowerCase()方法,又当作函数调用

    // Accessing the property 'toLowerCase'
    // on 'message' and then calling it
    message.toLowerCase();
    // Calling 'message'
    message();
    
  • 例子2,访问不存在的属性

    const user = {
    ​
      name: "Daniel",
    ​
      age: 26,
    ​
    };
    ​
    user.location; // returns undefined
    
  • 例子3,函数两个参数只传1个

    // This is an industrial-grade general-purpose greeter function:
    function greet(person, date) {
      console.log(`Hello ${person}, today is ${date}!`);
    }
    greet("Brendan");
    
  • 例子4,应该传Date传了字符串,下面应该调用时传new Date()

    function greet(person: string, date: Date) {
      console.log(`Hello ${person}, today is ${date.toDateString()}!`);
    }
    greet("Maddison", Date());
    //Argument of type 'string' is not assignable to parameter of type 'Date'.
    

2、安装及基本使用。

  • 安装,当然前提是有npm环境。

    npm install -g typescript
    
  • 使用,浏览器是不识别TypeScript的,先要编译成JavaScript,运行如下命令会生成hello.js。

    tsc hello.ts
    

3、常用类型(Everyday Types)。

JavaScript原生的类型string, number,boolean

Arrays,两种声明方式:普通、范型。

联合类型,中间用|分开,使用特定方法时需要做类型判断。

4、类型的自动推导,有利有弊。

5、对象

声明方式:type与interface,或者传参数时仅仅用一个结构体。

type是类型别名,interface是定义对象类型,二者很多相似性。主要区别有定义子类型的方式及属性添加。

  • 定义子类型的方式,用interface:
interface Animal {
  name: string
}
​
interface Bear extends Animal {
  honey: boolean
}
​
const bear = getBear() 
bear.name
bear.honey
        

用type定义子类型:

type Animal = {
  name: string
}
​
type Bear = Animal & { 
  honey: boolean 
}
​
const bear = getBear();
bear.name;
bear.honey;
        
  • 属性添加,inteface可以进行属性添加:
interface Window {
  title: string
}
​
interface Window {
  ts: TypeScriptAPI
}
​
const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});

type则不能进行属性添加:

type Window = {
  title: string
}
​
type Window = {
  ts: TypeScriptAPI
}
​
 // Error: Duplicate identifier 'Window'.

明天继续学习类型断言,待续。