将函数返回值限制为void

时间:2018-05-15 18:59:02

标签: typescript

let foo = () => 'foo'; let bar: () => void = foo; // produces no error 应该是一个没有返回值的函数:

bar

是否可以阻止为() => void分配与预期declare let jsApiThatShouldNeverAcceptTypeofFoo = (bar: () => void) => void; jsApiThatShouldNeverAcceptTypeofFoo(bar); 签名不匹配的功能?

例如,在这种情况下:

^/(?:[^/]+/){2}([^/]+)

2 个答案:

答案 0 :(得分:1)

不,因为void返回函数可赋值给返回值函数。另一方面,如果您期望返回void函数,则不能使用返回值。即。

let foo = () => 'foo';
let bar: () => void = foo; // produces no error

const result = bar(); // foo in runtime, TypeScript thinks it's void
const upper = result.toUpperCase(); // compile error

答案 1 :(得分:1)

部分解决方法是确保函数的返回类型没有键。这由void满足,但也由{}never满足。这可能足够接近,因为重新调整never的函数应该抛出错误并且返回{}的函数不经常发生:

type EnsureVoid<T> = keyof T extends never ? 
    void 
    : "Should not have a return type, only ()=> void is allowed";

declare let jsApiThatShouldNeverAcceptTypeofFoo: <T extends EnsureVoid<T>>(bar: ()=> T) => void;

let foo = () => 'foo';
jsApiThatShouldNeverAcceptTypeofFoo(foo)  // Error 


let bar = () => { };
jsApiThatShouldNeverAcceptTypeofFoo(bar)


let baz = () => ({ });
jsApiThatShouldNeverAcceptTypeofFoo(baz)

let boo = () => { throw "Error" };
jsApiThatShouldNeverAcceptTypeofFoo(boo)