导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

冷门技能

Untitled

简单类型

Untitled

普通对象的兼容

Untitled

type Person = {
  name: string
  age: number
}
let user = {
  name: 'Lance',
  age: 18,
  id: 1,
  email: '[email protected]'
}
let p: Person
p = user
let user = {
  name: 'Lance',
  age: 18,
  id: 1,
  email: '[email protected]'
}
type User = typeof user

Untitled

父子接口类型兼容

Untitled

复杂的函数兼容

Untitled

let fn1 = (a: number) => {
  console.log(a);
}
let fn2 = (b: number, s: string) => {
  console.log(b, s);
}
fn2 = fn1 // OK
fn1 = fn2 // 报错

Untitled

Untitled

interface MyEvent {
  target: string
}
interface MyMouseEvent extends MyEvent {
  x: number
  y: number
}
let listener = (e: MyEvent) => console.log(e.target);
let mouseListener = (e: MyMouseEvent) => console.log(e.x, e.y);
mouseListener = listener
listener = mouseListener

Untitled

Untitled

interface MyEvent {
  target: number
}
interface MyMouseEvent extends MyEvent {
  x: number
  y: number
}
function listenEvent(eventType: string, fn: (e: MyEvent) => void) {
 /* ... */ 
}
// 我们希望这样用
listenEvent('click', (e: MyMouseEvent) => console.log(e.x + ',' + e.y))
// 但只能这样用
listenEvent('click', (e: MyEvent) => {
  console.log((e as MyMouseEvent).x + ',' + (e as MyMouseEvent).y);
})
// 还可以这样用
listenEvent('click', ((e: MyMouseEvent) => 
  console.log(e.x + ',' + e.y)) as (e: MyEvent) => void);
// 这个就太离谱了
listenEvent('click', (e: number) => console.log(e))

Untitled

返回值类型不同的兼容

Untitled

let a = () => {
  return { name: 'Lance' }
}
let b = () => {
  return { name: 'La', age: 23 }
}
b = a // 报错
a = b // OK

赋值表

Untitled

顶类型、底类型

JSON类型定义

type JSONValue =
  | string
  | number
  | null
  | boolean
  | JSONValue[]
  | { [k: string]: JSONValue }
// 最后一个无线递归