Typescript function can return Promise as Promise?'unknown' vs. 'any'Are strongly-typed functions as parameters possible in TypeScript?Why is object.constructor a “Function”, and not “newable” in TypeScript?Typescript type enforce on promise typesCan I define a generic typescript Interface for the methods of a Class?Why can't I view json inside fetch's Response object in the developer console?Checking the structure of an object returned by a http service against a typescript interfacePromise fetch returning Promise<void | T> instead of expected objectcross-fetch doesn't work with React NativeTypeScript: Conditionally declare the return type of a functionHow to wrap JavaScript fetch in a function - unhandled promise rejection

Is there a minimum amount of electricity that can be fed back into the grid?

Minor differences between two recorded guitars

How to deal with a Murder Hobo Paladin?

Is reasonable to assume that the 食 in 月食/日食 can be interpreted as the sun/moon being "eaten" during an eclipse?

Merge overlapped intervals in a list

Did William Shakespeare hide things in his writings?

Attach a visible light telescope to the outside of the ISS

Extruder problem

What do I need to see before Spider-Man: Far From Home?

Earliest example of double planets in science fiction?

Why do most airliners have underwing engines, while business jets have rear-mounted engines?

Why does "sattsehen" take accusative "mich", not dative "mir"? Even though it is not "me" that I'm looking at?

Why does this function pointer assignment work when assigned directly but not with the conditional operator?

How to pass rendering parameters for a static controller rendering

How can I use my cell phone's light as a reading light?

How do I check that users don't write down their passwords?

Why is there paternal, for fatherly, fraternal, for brotherly, but no similar word for sons?

How predictable is $RANDOM really?

Linear transformations and eigen values

Why would "dead languages" be the only languages that spells could be written in?

Is this standard Japanese employment negotiations, or am I missing something?

Do intermediate subdomains need to exist?

Tiny URL creator

How to play a D major chord lower than the open E major chord on guitar?



Typescript function can return Promise as Promise?


'unknown' vs. 'any'Are strongly-typed functions as parameters possible in TypeScript?Why is object.constructor a “Function”, and not “newable” in TypeScript?Typescript type enforce on promise typesCan I define a generic typescript Interface for the methods of a Class?Why can't I view json inside fetch's Response object in the developer console?Checking the structure of an object returned by a http service against a typescript interfacePromise fetch returning Promise<void | T> instead of expected objectcross-fetch doesn't work with React NativeTypeScript: Conditionally declare the return type of a functionHow to wrap JavaScript fetch in a function - unhandled promise rejection






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I'm creating a type-safe wrapper for the fetch-api, and I noticed that the typescript compiler classifies this as perfectly valid code:



function foo(response: Response): Promise<Bar> //response received from a fetch() call
const json: Promise<any> = response.json();
return json; //Promise<any> can be returned as Promise<Bar>?



Why is it possible to directly return a Promise<any> as Promise<Bar>? Shouldn't this require some kind of type assertion?










share|improve this question




























    2















    I'm creating a type-safe wrapper for the fetch-api, and I noticed that the typescript compiler classifies this as perfectly valid code:



    function foo(response: Response): Promise<Bar> //response received from a fetch() call
    const json: Promise<any> = response.json();
    return json; //Promise<any> can be returned as Promise<Bar>?



    Why is it possible to directly return a Promise<any> as Promise<Bar>? Shouldn't this require some kind of type assertion?










    share|improve this question
























      2












      2








      2








      I'm creating a type-safe wrapper for the fetch-api, and I noticed that the typescript compiler classifies this as perfectly valid code:



      function foo(response: Response): Promise<Bar> //response received from a fetch() call
      const json: Promise<any> = response.json();
      return json; //Promise<any> can be returned as Promise<Bar>?



      Why is it possible to directly return a Promise<any> as Promise<Bar>? Shouldn't this require some kind of type assertion?










      share|improve this question














      I'm creating a type-safe wrapper for the fetch-api, and I noticed that the typescript compiler classifies this as perfectly valid code:



      function foo(response: Response): Promise<Bar> //response received from a fetch() call
      const json: Promise<any> = response.json();
      return json; //Promise<any> can be returned as Promise<Bar>?



      Why is it possible to directly return a Promise<any> as Promise<Bar>? Shouldn't this require some kind of type assertion?







      typescript promise fetch-api






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 20:29









      superbadcodemonkeysuperbadcodemonkey

      828 bronze badges




      828 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          6














          Always avoid any. any by definition is assignable to anything and assignable from anything without any sort of type assertions. When used as a generic type argument, the resuting type (ex Promise<any>) will generally be assignable to any other instantiation with any other type argument on that position (ex Promise<Bar>).



          Since 3.0 typescript introduced unknown (read here for more) which is similar to any in that you can assign anything to it, it is not assignable to anything else without a type assertion. So this is an error:



          let u: Promise<unknown>
          let n: Promise<number> = u; // error


          You might aslo look into tslint rules no-unsafe-any and no-any that prevent usage of any in a project, depending on how far you want to go with banning any, and like I said in the beginning I would ban it completely and add exceptions for the few cases where it is absolutely necessary.






          share|improve this answer

























          • That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

            – superbadcodemonkey
            Mar 25 at 20:44











          • @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

            – Titian Cernicova-Dragomir
            Mar 25 at 20:49


















          4














          If something can be anything it can also be a Bar. If you look at the Typescript documentation for Basic Types it says (emphasis mine)




          Any



          We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:




          Which means that the any type completely ignores compile-time type checks.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345934%2ftypescript-function-can-return-promiseany-as-promisebar%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            Always avoid any. any by definition is assignable to anything and assignable from anything without any sort of type assertions. When used as a generic type argument, the resuting type (ex Promise<any>) will generally be assignable to any other instantiation with any other type argument on that position (ex Promise<Bar>).



            Since 3.0 typescript introduced unknown (read here for more) which is similar to any in that you can assign anything to it, it is not assignable to anything else without a type assertion. So this is an error:



            let u: Promise<unknown>
            let n: Promise<number> = u; // error


            You might aslo look into tslint rules no-unsafe-any and no-any that prevent usage of any in a project, depending on how far you want to go with banning any, and like I said in the beginning I would ban it completely and add exceptions for the few cases where it is absolutely necessary.






            share|improve this answer

























            • That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

              – superbadcodemonkey
              Mar 25 at 20:44











            • @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

              – Titian Cernicova-Dragomir
              Mar 25 at 20:49















            6














            Always avoid any. any by definition is assignable to anything and assignable from anything without any sort of type assertions. When used as a generic type argument, the resuting type (ex Promise<any>) will generally be assignable to any other instantiation with any other type argument on that position (ex Promise<Bar>).



            Since 3.0 typescript introduced unknown (read here for more) which is similar to any in that you can assign anything to it, it is not assignable to anything else without a type assertion. So this is an error:



            let u: Promise<unknown>
            let n: Promise<number> = u; // error


            You might aslo look into tslint rules no-unsafe-any and no-any that prevent usage of any in a project, depending on how far you want to go with banning any, and like I said in the beginning I would ban it completely and add exceptions for the few cases where it is absolutely necessary.






            share|improve this answer

























            • That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

              – superbadcodemonkey
              Mar 25 at 20:44











            • @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

              – Titian Cernicova-Dragomir
              Mar 25 at 20:49













            6












            6








            6







            Always avoid any. any by definition is assignable to anything and assignable from anything without any sort of type assertions. When used as a generic type argument, the resuting type (ex Promise<any>) will generally be assignable to any other instantiation with any other type argument on that position (ex Promise<Bar>).



            Since 3.0 typescript introduced unknown (read here for more) which is similar to any in that you can assign anything to it, it is not assignable to anything else without a type assertion. So this is an error:



            let u: Promise<unknown>
            let n: Promise<number> = u; // error


            You might aslo look into tslint rules no-unsafe-any and no-any that prevent usage of any in a project, depending on how far you want to go with banning any, and like I said in the beginning I would ban it completely and add exceptions for the few cases where it is absolutely necessary.






            share|improve this answer















            Always avoid any. any by definition is assignable to anything and assignable from anything without any sort of type assertions. When used as a generic type argument, the resuting type (ex Promise<any>) will generally be assignable to any other instantiation with any other type argument on that position (ex Promise<Bar>).



            Since 3.0 typescript introduced unknown (read here for more) which is similar to any in that you can assign anything to it, it is not assignable to anything else without a type assertion. So this is an error:



            let u: Promise<unknown>
            let n: Promise<number> = u; // error


            You might aslo look into tslint rules no-unsafe-any and no-any that prevent usage of any in a project, depending on how far you want to go with banning any, and like I said in the beginning I would ban it completely and add exceptions for the few cases where it is absolutely necessary.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 25 at 20:43

























            answered Mar 25 at 20:36









            Titian Cernicova-DragomirTitian Cernicova-Dragomir

            86.2k5 gold badges70 silver badges83 bronze badges




            86.2k5 gold badges70 silver badges83 bronze badges












            • That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

              – superbadcodemonkey
              Mar 25 at 20:44











            • @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

              – Titian Cernicova-Dragomir
              Mar 25 at 20:49

















            • That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

              – superbadcodemonkey
              Mar 25 at 20:44











            • @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

              – Titian Cernicova-Dragomir
              Mar 25 at 20:49
















            That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

            – superbadcodemonkey
            Mar 25 at 20:44





            That makes a lot of sense. Is there a reason why Body.json() returns Promise<any> instead of Promise<unknown>?

            – superbadcodemonkey
            Mar 25 at 20:44













            @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

            – Titian Cernicova-Dragomir
            Mar 25 at 20:49





            @superbadcodemonkey It would break a lot of code if it did. There is a GH discussion to add an option to use unknown instead of any in lib.d.ts but I can't find it right now and I don't think it will be implemented any time soon.

            – Titian Cernicova-Dragomir
            Mar 25 at 20:49













            4














            If something can be anything it can also be a Bar. If you look at the Typescript documentation for Basic Types it says (emphasis mine)




            Any



            We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:




            Which means that the any type completely ignores compile-time type checks.






            share|improve this answer



























              4














              If something can be anything it can also be a Bar. If you look at the Typescript documentation for Basic Types it says (emphasis mine)




              Any



              We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:




              Which means that the any type completely ignores compile-time type checks.






              share|improve this answer

























                4












                4








                4







                If something can be anything it can also be a Bar. If you look at the Typescript documentation for Basic Types it says (emphasis mine)




                Any



                We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:




                Which means that the any type completely ignores compile-time type checks.






                share|improve this answer













                If something can be anything it can also be a Bar. If you look at the Typescript documentation for Basic Types it says (emphasis mine)




                Any



                We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:




                Which means that the any type completely ignores compile-time type checks.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 20:36









                DanielDaniel

                6,3658 gold badges23 silver badges51 bronze badges




                6,3658 gold badges23 silver badges51 bronze badges



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55345934%2ftypescript-function-can-return-promiseany-as-promisebar%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript