Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

第224题:TypeScript中的never类型具体有什么用?

Open sisterAn opened this issue 4 years ago • 3 comments

sisterAn avatar Sep 01 '21 23:09 sisterAn

举个具体点的例子,当你有一个 union type:

interface Foo {
  type: 'foo'
}

interface Bar {
  type: 'bar'
}

type All = Foo | Bar

在 switch 当中判断 type,TS 是可以收窄类型的 (discriminated union):

function handleValue(val: All) {
  switch (val.type) {
    case 'foo':
      // 这里 val 被收窄为 Foo
      break
    case 'bar':
      // val 在这里是 Bar
      break
    default:
      // val 在这里是 never
      const exhaustiveCheck: never = val
      break
  }
}

注意在 default 里面我们把被收窄为 never 的 val 赋值给一个显式声明为 never 的变量。如果一切逻辑正确,那么这里应该能够编译通过。但是假如后来有一天你的同事改了 All 的类型:type All = Foo | Bar | Baz 然而他忘记了在 handleValue 里面加上针对 Baz 的处理逻辑,这个时候在 default branch 里面 val 会被收窄为 Baz,导致无法赋值给 never,产生一个编译错误。所以通过这个办法,你可以确保 handleValue 总是穷尽 (exhaust) 了所有 All 的可能类型。

引用链接:https://www.zhihu.com/question/354601204/answer/888551021

JTangming avatar Sep 12 '21 14:09 JTangming

never的作用是可以确保条件收窄不会遗漏,如有遗漏会出现类型报错

zhangtaolei avatar Nov 23 '21 09:11 zhangtaolei

在“类型体操”中,never 一般用作于对联合类型的过滤或删除操作:

// 内置类型方法 Exclude
type Exclude<T, U> = T extends U ? never : T

type Test = Exclude<'a' | 'b' | 'c', 'b'> // 'a' | 'c'

type A = 'a' | never // 'a'

anotherso1a avatar Feb 28 '22 09:02 anotherso1a