xxleyi / learning_list

聚集自己的学习笔记
10 stars 3 forks source link

5.1 Coproducts, sum types #307

Open xxleyi opened 3 years ago

xxleyi commented 3 years ago

image

sum 类型是个好东西,下面的代码是一段使用了 overloading 功能 TS,在本质上模拟了 Haskell 中处理 Either type 入参函数的定义形式。

// using overloading to implement function which handle Either type
function t(a: number) : string
function t(a: string) : boolean
function t(a: number | string) {
  if (typeof a === 'number') {
    return `${a}`
  } else {
    return a.indexOf('a') > -1
  }
}