TypeScript一问一答05 语法规范简析

121 阅读1分钟

初篇

TypeScript扩展了JavaScript的哪些声明?

扩展了三个声明 interfacr type enum

interface InterfaceDeclaration {}

type TypeAliasDeclaration = string;

enum EnumDeclaration {}

你知道any的所有subtype吗?

any,跳脱了TypeScript类型系统的束缚
如下图所示

好的,让我们开始实战吧

进阶

Ambient Declaration是什么?

向TypeScript编译时的作用域插入全局类型,方便不改写老的JavaScript代码,同时拥有TypeScript的类型系统,例如jquery

declare var $:any

Function Type 是什么 ?

闭包是JavaScript函数提供的重要能力

闭包指的是函数在定义时可以捕捉到上级作用域所有信息的能力

type FnType = (n: number) => void // Function Type
interface FnInterface {
  (n: number): void
}

引入函数类型以后可以定义函数的重载

class Employee {}

//Overload Signature 1
function findEmployees(name: string): Employee[]; 
//Overload Signature 2
function findEmployees(name: string, age: number): Employee[]; 	
//Overload Signature 3
function findEmployees(name: string, age: number, location: string): Employee[]; 	
//Implementation Signature 实际定义
function findEmployees(name: string, age?: number, location?: string): Employee[] {   

	let employee: Employee[] = [];

  if(age != undefined && location != undefined) {
    //find employees by name, age and location
  } else {
    //find employees by name and age
  }

	return employee;
}

Object Types是什么?

interface Obj {
  name: string
}

类型推断(Type Inference)是什么 ?

类型推断指TypeScript会根据代码在编写时所处的上下文自动推断类型
最简单的例子

let numInference = 1 // 

image.png
根据输入参数推断输出类型

function mul(a: number, b: number) {
 return a * b; // 自动推断 number类型
}

image.png
Array类型推断

let numInference = [1, '1']

image.png

namespace的基本使用?

自执行函数实现的小型模块化

namespace M {
 var s = "hello";
 export function f() {
 return s;
 }
}
// 等同于利用闭包实现的模块化

// namespace
var M;
(function (M) {
    var s = "hello";
    function f() {
        return s;
    }
    M.f = f;
})(M || (M = {}));

Enum Types 基本语法 ?

const enum Operator {
  ADD,
  DIV,
  MUL,
  SUB
}