TS文档说," never 类型表示从未发生过的值的类型。当任何类型的守卫变得狭隘时,变量也会获得永远类型。"
我没有理解它的用法,有人可以用一些例子给我回答。
答案 0 :(得分:7)
可能是永不返回的函数的返回类型:
const reportError = function () {
throw Error('my error');
}
const loop = function () {
while(true) {}
}
此处,reportError
和loop
的类型均为() => never
。
使用typeof
,instanceof
或in
之类的运算符,我们可以缩小变量类型的范围。我们可以缩小类型的范围,以确保在某些地方不会发生此变量。
function format(value: string | number) {
if (typeof value === 'string') {
return value.trim();
} else {
return value.toFixed(2); // we're sure it's number
}
// not a string or number
// "value" can't occur here, so it's type "never"
}
除了更好的类型安全性(如上述情况)外,never
类型还有另一个用例-条件类型。使用never
类型,我们可以排除一些不需要的类型:
type NonNullable<T> = T extends null | undefined ? never : T;
type A = NonNullable<boolean>; // boolean
type B = NonNullable<number | null>; // number
答案 1 :(得分:5)
Typescript documentation for never中有多个示例:
// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
答案 2 :(得分:2)
一个例子是如果你抛出一个错误。 E.g。
function throwError () {
throw new Error('whoops');
}
您可以在此处找到更多信息:https://basarat.gitbooks.io/typescript/content/docs/types/never.html
答案 3 :(得分:2)
我研究过的链接: https://www.typescriptlang.org/docs/handbook/basic-types.html https://basarat.gitbooks.io/typescript/docs/types/never.html https://egghead.io/lessons/typescript-use-the-never-type-to-avoid-code-with-dead-ends-using-typescript https://blog.mariusschulz.com/2016/11/18/typescript-2-0-the-never-type
可以总结为Never类型用于诸如此类的情况:
函数从不返回(例如,如果函数主体具有while(true){}
)
//Type () => never
const sing = function() {
while (true) {
console.log("Never gonna give you up");
console.log("Never gonna let you down");
console.log("Never gonna run around and desert you");
console.log("Never gonna make you cry");
console.log("Never gonna say goodbye");
console.log("Never gonna tell a lie and hurt you");
}
};
一个函数总是抛出(例如在函数foo(){throw new Error('Not Implemented')}
中)
foo的返回类型永远不会)
// Type (message: string) => never
const failwith = (message: string) => {
throw new Error(message);
};
用例:详尽的检查
function foo(x: string | number): boolean {
if (typeof x === "string") {
return true;
} else if (typeof x === "number") {
return false;
}
// Without a never type we would error :
// - Not all code paths return a value (strict null checks)
// - Or Unreachable code detected
// But because TypeScript understands that `fail` function returns `never`
// It can allow you to call it as you might be using it for runtime safety / exhaustive checks.
return fail("Unexhaustive!");
}
function fail(message: string): never { throw new Error(message); }
答案 4 :(得分:0)
ArrayList<Object> s = new ArrayList<>(); s.add("test"); s.add(null); try { System.out.println(s + "\n"); for (Object t : s) { System.out.println(t); if (t != null && t.equals("test")) { s.remove(t); System.out.println("ObjectRemoved = " + t + "\n"); } } System.out.println(s + "\n"); } catch (ConcurrentModificationException e) { System.out.println(e); } catch (Exception e) { System.out.println(e); }
类型表示永远不会出现的值的类型:
Typescript编译器将类型分配给所有变量/属性。这些类型可以是never
和number
等打字稿定义的类型,也可以是用string
和interface
关键字制成的用户定义的类型。
将这些类型视为集合很有用。换句话说,类型本身就是可能变量/属性在那时可能存在的事物的集合。例如:
type
现在请牢记我们的集合定义,我们可以轻松定义// the variable five can be one thing which is a number
const foo = 5; // type = number;
// bar can be two things
type twoPrimitives = string | number;
let bar: twoPrimitives = 4;
类型:
never
类型代表空类型集>> {} 。即其中包含0个项目的集合。
例如:
never
变量也永远不会通过任何永远不可能为真的类型防护来缩小类型。
如果在if语句中显式检查了窄类型,则TS可以检查它们。这称为类型防护。换句话说,类型保护是某种表达式,它执行运行时检查以确保在特定范围内的类型。例如:
// Normally a function which do not have a return value returns undefined implicitly
// However this function throws before ever reaching the end.
// Therefore the return type will be never
function foo() :never {
throw new Error("Error");
}
// thisMakesNoSense will be type never, a value can never be number and string at the same time
type thisMakesNoSense = number & string;