Typescript应用

133 阅读2分钟

必要的特性

Readonly

ES6 -> const
const 定义的变量是引用类型,依然可以改变属性

使用readonly对属性或者变量声明,编译阶段会给出警告

namespae

常用于组织一份类型区域防止类型之间的重命名冲突,需要配置 declare 输出到外部环境才能够使用,非常便捷的在于使用declare namespace在工程项目中可以不需要引入任何类型而直接可以访问

declare

declare是用于声明形式存在的。

  • declare var/let/const用来声明全局的变量。
  • declare function 用来声明全局方法(函数)
  • declare class 用来声明全局类
  • declare namespace 用来声明命名空间
  • declare module 用来声明模块

declare在模块文件中定义为模块文件的全局变量,如果变量想用作全局呢?

declare global就可以满足需求

函数重载

大多数用于多态函数。大多数同学可能都不怎么使用。但是它能够定义不同的参数类型。需要有多个重载签名和一个实现签名

  • 重载签名:就是对参数形式的不同书写,可以定义多种模式。
  • 实现签名:对函数内部方法的具体实现。

\

建议

减少重复代码

interface Person {
  firstNamestring;
  lastNamestring;
}

interface PersonWithBirthDate {
  firstNamestring;
  lastNamestring;
  birthDate;
}

PersonWithBirthDate接口只是多了birth属性,可以利用extends来解决 或者交叉运算符来解决

interface Person { 
  firstName: string; 
  lastName: string;
}

interface PersonWithBirthDate extends Person { 
  birth: Date;
}


type PersonWithBirthDate = Person & { birthDate };

实际开发中

函数有相同的类型签名

function get(url: string, opts: Options): Promise<Response> { /* ... */ } 
function post(url: string, opts: Options): Promise<Response> { /* ... */ }
type HTTPFunction = (url: string, opts: Options) => Promise<Response>; 
const getHTTPFunction = (url, opts) => { /* ... */ };
const postHTTPFunction = (url, opts) => { /* ... */ };

使用更精确的类型替代字符串类型

interface Pop = {
  popdate: string// 日期:YYYY-MM-DD
  popType: string// 类型:"success" 或 "fail"
};


const dialog: Pop = {
  popdate: 'November 31, 1991', // 与预期格式不匹配
  popType: 'Fail' // 与预期格式不匹配
}

这种情况 TS编译器并不能发现问题,

interface Pop = {
  popdate: Date, // 日期:YYYY-MM-DD
  popType: "success" | "fail"// 类型:"success" 或 "fail"
};