我知道下面的内容并不意味着返回的"type"是void。我所理解的是,voidFunc不返回任何内容,因为它返回的是"void"。为什么它返回任何类型?
type voidFunc = () => void
const myFunc: voidFunc = () => {
return 'hello'
}
它和下面写的有什么不同?type voidFunc = () => any
参见功能的可分配性
返回类型无效
函数的void返回类型可能会产生一些不寻常但预期的行为。
返回类型为void
的上下文类型不会强制函数返回内容。另一种说法是,具有void
返回类型(type vf = () => void
(的上下文函数类型在实现时可以返回任何其他值,但它将被忽略。
因此,以下类型() => void
的实现是有效的:
type voidFunc = () => void;
const f1: voidFunc = () => {
return true;
};
const f2: voidFunc = () => true;
const f3: voidFunc = function () {
return true;
};
当其中一个函数的返回值被分配给另一个变量时,它将保留void的类型:
const v1 = f1();
const v2 = f2();
const v3 = f3();