void as a type of an argument of a generic function in TypeScript
It is possible to use void
as a type argument, but you shouldn't use it as a type.
In fact, although you may be able to use it in a type annotation currently, it is impossible to assign a value:
var x: void = ???; // cannot supply a value
The use of void as a type argument is illustrated below:
class Example<TReturn> {
process(func: () => TReturn) {
return func();
}
}
The type argument in this class is used to specify the return type of a function. That means that I may wish to specify that the function will have the void
type. So it must be allowed as a type argument.
var example = new Example<void>();
Now when I write the call to example.process
, auto-completion will tell me that the argument I pass needs to satisfy the following type:
func: () => void
And it will also tell me that example.process
itself is void in this case.
The intention isn't for void
to ever be used to annotate a type, but because there are valid reasons to allow it as a type argument it isn't checked currently. It means you can create something invalid, but you'd be hard pressed to use it:
class Example<T> {
process(func: T) {
// if T is void, this is all wrong
}
}
var example = new Example<void>();
In this invalid example (which doesn't show any errors) you wouldn't be able to write a call to example.process
because you couldn't pass a valid argument.
From the TypeScript specification:
NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose. However, because Void is permitted as a type argument to a generic type or function it is not feasible to disallow Void properties or parameters.