如何在网站网站做代理,网站图片怎么替换,临漳专业做网站,教育机构网站建设加盟TypeScript 的 never 类型是一种特殊的类型#xff0c;它表示的是那些永远不存在的值的类型。例如#xff0c;一个抛出异常或无限循环的函数的返回值类型就是 never#xff0c;因为它们永远不会返回任何值。never 类型是所有类型的子类型#xff0c;也就是说#xff0c;任…TypeScript 的 never 类型是一种特殊的类型它表示的是那些永远不存在的值的类型。例如一个抛出异常或无限循环的函数的返回值类型就是 never因为它们永远不会返回任何值。never 类型是所有类型的子类型也就是说任何类型都可以赋值给 never 类型但是 never 类型只能赋值给自己和 any 类型。never 类型有以下的特点和用途https://juejin.cn/post/7201048368389914682
• never 类型不能被实例化也不能有任何值甚至 undefined 也不行。
• never 类型可以用来表示不可能发生的情况例如在 switch 语句中的 default 分支或者在类型保护中排除掉所有可能的情况。
• never 类型可以用来进行疲劳性检查exhaustiveness check也就是检查是否所有的分支都被覆盖到了如果有遗漏就会报错。
下面是一些使用 never 类型的例子
// 抛出异常的函数的返回值类型是 never
function throwError(message: string): never {throw new Error(message);
}// 无限循环的函数的返回值类型也是 never
function loopForever(): never {while (true) {}
}// 使用 never 类型来表示不可能发生的情况
type Direction up | down | left | right;function move(direction: Direction) {switch (direction) {case up:// do somethingbreak;case down:// do somethingbreak;case left:// do somethingbreak;case right:// do somethingbreak;default:// 如果有遗漏的情况就会报错const invalid: never direction;// Error: Type string is not assignable to type never}
}// 使用 never 类型来进行疲劳性检查
class ExhaustiveError extends Error {constructor(value: never, message?: string) {super(message);}
}function checkExhaustive(value: Direction) {switch (value) {case up:// do somethingbreak;case down:// do somethingbreak;default:// 如果有遗漏的情况就会抛出异常throw new ExhaustiveError(value);// Error: Argument of type string is not assignable to parameter of type never}
}