1. 函数没有返回值:
function logMessage(message: string): void {
console.log(message);
}
在这个例子中,
2. 变量的
let unusable: void = undefined;
3. 主要用于函数:
// 使用 undefined 或 null let myVariable: undefined = undefined; let myConstant: null = null; // let myVoidVariable: void = undefined; // 错误,因为 void 类型不能直接用于变量声明
4. 与
-
void 表示没有返回值的函数类型,而undefined 和null 是表示变量可以被赋值的两个特殊值。 -
在函数返回类型上,使用
void 表示函数不返回值,而在变量声明时使用void 则表示该变量只能被赋值为undefined 或null 。
function performAction(): void {
// 执行某些操作
console.log("Action performed");
}
let result: void = performAction(); // OK,因为 performAction 没有返回值
let variable: void = undefined; // OK
// let variable: void = 10; // 错误,因为 void 类型只能为 undefined 或 null
总的来说,