void as a type of an argument of a generic function in TypeScript

前端 未结 7 1252
遥遥无期
遥遥无期 2021-01-11 09:37

It is possible to specify void as a type parameter for generic function in TypeScript. And it works fine for return values of functions. However when void

相关标签:
7条回答
  • 2021-01-11 10:11

    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.

    0 讨论(0)
提交回复
热议问题