记录、分享、学习

Notes on TypeScript

2 min

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

笔记

  1. Core Types
  • number
  • string
  • boolean
  1. TypeScript Type vs JavaScript Type JS 的是dynamic types,在运行时执行;

TS 的是static types,在开发阶段被设定。

  1. Generics(泛型)
// interface 的入参类型是个变量 ContentType
  
// 函数 save 接受的参数 a 的类型也指定为 ContentType
  
interface CacheHostGeneric<ContentType> {
  
  save: (a: ContentType) => void;
  
}
  
// 入参类型分别为 Type 和 Cache,其中 Cache 继承自 CacheHostGeneric 类型
  
// 第一次参数 obj 的泛型是 Type,第二个参数 cache 的泛型是 Cache
  
// return 泛型是 Cache
  
function addTypedObjectToCache<Type, Cache extends CacheHostGeneric<Type>>(obj: Type, cache: Cache): Cache {
  
  cache.save(obj);
  
  return cache;
  
}
  
// OUTPUT >> save cache: cache content
  
addTypedObjectToCache('cache content', {
  
  save: x => {
  
    console.log('save cache: ' + x);
  
  }
  
});
  
  1. 函数的入参类型
interface AnyObjectButMustHaveName {
  
  name: string
  
  [key: string]: any // 其他自定义字段,类型不限 any
  
}
  
const printFormattedName = (input: AnyObjectButMustHaveName) => {
  
  console.log(input);
  
}
  
printFormattedName({name: "joey"})
  
printFormattedName({name: "joey", age: 23})
  
printFormattedName({name: "joey", age: 23, sex: 'female'})
  
// 同一个入参,支持不同类型
  
const boolOrNumberFunction = (input: boolean | number) => {}
  
interface BoolOrNumberOrStringFunction {
  
  /** Takes a bool, returns a bool */
  
  (input: boolean): boolean
  
  /** Takes a number, returns a number */
  
  (input: number): number
  
  /** Takes a string, returns a bool */
  
  (input: string): boolean
  
}
  
// 在 ts 运行即使函数不存在,有 declare 会告诉 ts 这是存在的(注意:declare 没有赋值函数体,在运行 js 还是会报错的)
  
// declare 去掉后,由于 boolOrNumberOrStringFunction 只声明了类型,没有具体的函数体,TS 编译时会报错
  
declare const boolOrNumberOrStringFunction: BoolOrNumberOrStringFunction
  
const boolValue = boolOrNumberOrStringFunction(true)
  
const numberValue = boolOrNumberOrStringFunction(12)
  
const boolValue2 = boolOrNumberOrStringFunction('string')
  

TypeScript in 5 minutes

优势:

  • 类型检查
  • 下一代 JS 特性的超集(编译成原生 JS,在老浏览器中使用)
  • 一些非 JS 的特性,如 Interface(接口)或 Generics(泛型)
  • 元编程(meta programming)的特性,如 Decorators(装饰器)
  • 丰富的配置扩展(各种 loader)
  • 更多现代工具的支持

安装

npm install -g typescript
  

编译

TS 并不能原生地在浏览器或者 node 环境运行,需要被编译为原生的 JS 后,再运行。

tsc demo.ts
  

OUTPUT >> demo.js