never 永不存在的值得类型,不好理解,以实例为例:

函数
返回never的函数必须存在无法到达的终点,更不好理解,这里并不是指没有返回值

never

 

 

 

而是指会抛出、返回错误或者无限循环

// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}

 

变量

永不为真的束缚(??)

常见于条件类型

type Exclude<T, U> = T extends U ? never : T;

// 相当于: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>

也常见于

let x:never = (()=>{ throw new Error('exception')})();

 

 

相关文章:

  • 2021-12-13
  • 2021-09-25
  • 2021-10-17
  • 2022-03-05
  • 2021-07-31
  • 2021-10-03
  • 2021-06-22
  • 2021-08-31
猜你喜欢
  • 2021-07-31
  • 2022-12-23
  • 2021-11-08
  • 2021-05-18
  • 2022-03-07
  • 2021-04-02
相关资源
相似解决方案