Could you explain why typescript guard doesn't work










1















With Typescript 3.1 I have got a following piece of code



type Variable = string | File;

function isFile(variable: Variable): variable is File
return (variable as File).name !== undefined;


function getFileFromVariables(entity: EntityInterface)
return isFile(this.state.variables[entity.variable])
? this.state.variables[entity.variable]
: undefined;


const file = getFileFromVariables(someEntity);


Unfortunately, I don't know why the file is
const file: string | File | undefined
instead of const file: File | undefined



Could someone tell me why it's like this and how may I fix it?










share|improve this question






















  • Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

    – Nurbol Alpysbayev
    Nov 14 '18 at 8:19







  • 1





    What is the type of this.state.variables?

    – Paleo
    Nov 14 '18 at 8:22
















1















With Typescript 3.1 I have got a following piece of code



type Variable = string | File;

function isFile(variable: Variable): variable is File
return (variable as File).name !== undefined;


function getFileFromVariables(entity: EntityInterface)
return isFile(this.state.variables[entity.variable])
? this.state.variables[entity.variable]
: undefined;


const file = getFileFromVariables(someEntity);


Unfortunately, I don't know why the file is
const file: string | File | undefined
instead of const file: File | undefined



Could someone tell me why it's like this and how may I fix it?










share|improve this question






















  • Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

    – Nurbol Alpysbayev
    Nov 14 '18 at 8:19







  • 1





    What is the type of this.state.variables?

    – Paleo
    Nov 14 '18 at 8:22














1












1








1








With Typescript 3.1 I have got a following piece of code



type Variable = string | File;

function isFile(variable: Variable): variable is File
return (variable as File).name !== undefined;


function getFileFromVariables(entity: EntityInterface)
return isFile(this.state.variables[entity.variable])
? this.state.variables[entity.variable]
: undefined;


const file = getFileFromVariables(someEntity);


Unfortunately, I don't know why the file is
const file: string | File | undefined
instead of const file: File | undefined



Could someone tell me why it's like this and how may I fix it?










share|improve this question














With Typescript 3.1 I have got a following piece of code



type Variable = string | File;

function isFile(variable: Variable): variable is File
return (variable as File).name !== undefined;


function getFileFromVariables(entity: EntityInterface)
return isFile(this.state.variables[entity.variable])
? this.state.variables[entity.variable]
: undefined;


const file = getFileFromVariables(someEntity);


Unfortunately, I don't know why the file is
const file: string | File | undefined
instead of const file: File | undefined



Could someone tell me why it's like this and how may I fix it?







javascript typescript typescript-typings






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 7:56









AbdizrielAbdizriel

145113




145113












  • Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

    – Nurbol Alpysbayev
    Nov 14 '18 at 8:19







  • 1





    What is the type of this.state.variables?

    – Paleo
    Nov 14 '18 at 8:22


















  • Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

    – Nurbol Alpysbayev
    Nov 14 '18 at 8:19







  • 1





    What is the type of this.state.variables?

    – Paleo
    Nov 14 '18 at 8:22

















Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

– Nurbol Alpysbayev
Nov 14 '18 at 8:19






Hi. What do you want to achieve? And what do you mean by this: "the file is const file: string | File | undefined instead of const file: File | undefined". In my setup file has type any.

– Nurbol Alpysbayev
Nov 14 '18 at 8:19





1




1





What is the type of this.state.variables?

– Paleo
Nov 14 '18 at 8:22






What is the type of this.state.variables?

– Paleo
Nov 14 '18 at 8:22













2 Answers
2






active

oldest

votes


















0














TypeScript isn't able to link together two instances of this.state.variables[entity.variable] - one that is passed into type guard and another used afterwards. For it, this is two unrelated queries into array, since entity.variable could be very well changed by some undercover process (or even by the type guard, if it is in the same scope), and type system isn't able to catch that.



A common workaround is to use the temporary variable:



type Variable = string | File;

function isFile(variable: Variable): variable is File
return (variable as File).name !== undefined;


function getFileFromVariables(entity: EntityInterface)
const variable = this.state.variables[entity.variable];
return isFile(variable) ? variable : undefined;


const file = getFileFromVariables(someEntity);



Side note: try to provide a self-contained example, in other words, an MCVE. Your code was impossible to check, since we don't know neither what EntityInterface interface looks like nor what is this or this.state. My answer is assuming that this.state.variables is of type Variable and EnintyInterface extends variable: number, and it's enough for the code provided to give you the result you ask, but please, don't force us to do this assumptions.






share|improve this answer






























    0














    Your question is pretty vague.



    Other than that, all the problems you are encountering are from non-strict mode and some other poor practices. I suggest you the following:



    • Add "strict": true to compilerOptions of tsconfig.json (at least temporarily, until you figure out the solution to your problem)

    • Define explicitly what you want to get from a function e.g. getFileFromVariables(...): File | undefined

    • If possible, don't use classic functions for such cases. Instead define a type type GetFileFromVariables = (ent: EntityInterface) => File | undefined, then const getFileFromVariables: GetFileFromVariables = () => ...

    Then everything instantly becomes much clearer to you.






    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%2f53295381%2fcould-you-explain-why-typescript-guard-doesnt-work%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









      0














      TypeScript isn't able to link together two instances of this.state.variables[entity.variable] - one that is passed into type guard and another used afterwards. For it, this is two unrelated queries into array, since entity.variable could be very well changed by some undercover process (or even by the type guard, if it is in the same scope), and type system isn't able to catch that.



      A common workaround is to use the temporary variable:



      type Variable = string | File;

      function isFile(variable: Variable): variable is File
      return (variable as File).name !== undefined;


      function getFileFromVariables(entity: EntityInterface)
      const variable = this.state.variables[entity.variable];
      return isFile(variable) ? variable : undefined;


      const file = getFileFromVariables(someEntity);



      Side note: try to provide a self-contained example, in other words, an MCVE. Your code was impossible to check, since we don't know neither what EntityInterface interface looks like nor what is this or this.state. My answer is assuming that this.state.variables is of type Variable and EnintyInterface extends variable: number, and it's enough for the code provided to give you the result you ask, but please, don't force us to do this assumptions.






      share|improve this answer



























        0














        TypeScript isn't able to link together two instances of this.state.variables[entity.variable] - one that is passed into type guard and another used afterwards. For it, this is two unrelated queries into array, since entity.variable could be very well changed by some undercover process (or even by the type guard, if it is in the same scope), and type system isn't able to catch that.



        A common workaround is to use the temporary variable:



        type Variable = string | File;

        function isFile(variable: Variable): variable is File
        return (variable as File).name !== undefined;


        function getFileFromVariables(entity: EntityInterface)
        const variable = this.state.variables[entity.variable];
        return isFile(variable) ? variable : undefined;


        const file = getFileFromVariables(someEntity);



        Side note: try to provide a self-contained example, in other words, an MCVE. Your code was impossible to check, since we don't know neither what EntityInterface interface looks like nor what is this or this.state. My answer is assuming that this.state.variables is of type Variable and EnintyInterface extends variable: number, and it's enough for the code provided to give you the result you ask, but please, don't force us to do this assumptions.






        share|improve this answer

























          0












          0








          0







          TypeScript isn't able to link together two instances of this.state.variables[entity.variable] - one that is passed into type guard and another used afterwards. For it, this is two unrelated queries into array, since entity.variable could be very well changed by some undercover process (or even by the type guard, if it is in the same scope), and type system isn't able to catch that.



          A common workaround is to use the temporary variable:



          type Variable = string | File;

          function isFile(variable: Variable): variable is File
          return (variable as File).name !== undefined;


          function getFileFromVariables(entity: EntityInterface)
          const variable = this.state.variables[entity.variable];
          return isFile(variable) ? variable : undefined;


          const file = getFileFromVariables(someEntity);



          Side note: try to provide a self-contained example, in other words, an MCVE. Your code was impossible to check, since we don't know neither what EntityInterface interface looks like nor what is this or this.state. My answer is assuming that this.state.variables is of type Variable and EnintyInterface extends variable: number, and it's enough for the code provided to give you the result you ask, but please, don't force us to do this assumptions.






          share|improve this answer













          TypeScript isn't able to link together two instances of this.state.variables[entity.variable] - one that is passed into type guard and another used afterwards. For it, this is two unrelated queries into array, since entity.variable could be very well changed by some undercover process (or even by the type guard, if it is in the same scope), and type system isn't able to catch that.



          A common workaround is to use the temporary variable:



          type Variable = string | File;

          function isFile(variable: Variable): variable is File
          return (variable as File).name !== undefined;


          function getFileFromVariables(entity: EntityInterface)
          const variable = this.state.variables[entity.variable];
          return isFile(variable) ? variable : undefined;


          const file = getFileFromVariables(someEntity);



          Side note: try to provide a self-contained example, in other words, an MCVE. Your code was impossible to check, since we don't know neither what EntityInterface interface looks like nor what is this or this.state. My answer is assuming that this.state.variables is of type Variable and EnintyInterface extends variable: number, and it's enough for the code provided to give you the result you ask, but please, don't force us to do this assumptions.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 8:24









          CerberusCerberus

          986719




          986719























              0














              Your question is pretty vague.



              Other than that, all the problems you are encountering are from non-strict mode and some other poor practices. I suggest you the following:



              • Add "strict": true to compilerOptions of tsconfig.json (at least temporarily, until you figure out the solution to your problem)

              • Define explicitly what you want to get from a function e.g. getFileFromVariables(...): File | undefined

              • If possible, don't use classic functions for such cases. Instead define a type type GetFileFromVariables = (ent: EntityInterface) => File | undefined, then const getFileFromVariables: GetFileFromVariables = () => ...

              Then everything instantly becomes much clearer to you.






              share|improve this answer





























                0














                Your question is pretty vague.



                Other than that, all the problems you are encountering are from non-strict mode and some other poor practices. I suggest you the following:



                • Add "strict": true to compilerOptions of tsconfig.json (at least temporarily, until you figure out the solution to your problem)

                • Define explicitly what you want to get from a function e.g. getFileFromVariables(...): File | undefined

                • If possible, don't use classic functions for such cases. Instead define a type type GetFileFromVariables = (ent: EntityInterface) => File | undefined, then const getFileFromVariables: GetFileFromVariables = () => ...

                Then everything instantly becomes much clearer to you.






                share|improve this answer



























                  0












                  0








                  0







                  Your question is pretty vague.



                  Other than that, all the problems you are encountering are from non-strict mode and some other poor practices. I suggest you the following:



                  • Add "strict": true to compilerOptions of tsconfig.json (at least temporarily, until you figure out the solution to your problem)

                  • Define explicitly what you want to get from a function e.g. getFileFromVariables(...): File | undefined

                  • If possible, don't use classic functions for such cases. Instead define a type type GetFileFromVariables = (ent: EntityInterface) => File | undefined, then const getFileFromVariables: GetFileFromVariables = () => ...

                  Then everything instantly becomes much clearer to you.






                  share|improve this answer















                  Your question is pretty vague.



                  Other than that, all the problems you are encountering are from non-strict mode and some other poor practices. I suggest you the following:



                  • Add "strict": true to compilerOptions of tsconfig.json (at least temporarily, until you figure out the solution to your problem)

                  • Define explicitly what you want to get from a function e.g. getFileFromVariables(...): File | undefined

                  • If possible, don't use classic functions for such cases. Instead define a type type GetFileFromVariables = (ent: EntityInterface) => File | undefined, then const getFileFromVariables: GetFileFromVariables = () => ...

                  Then everything instantly becomes much clearer to you.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 14 '18 at 8:35

























                  answered Nov 14 '18 at 8:28









                  Nurbol AlpysbayevNurbol Alpysbayev

                  4,6411331




                  4,6411331



























                      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%2f53295381%2fcould-you-explain-why-typescript-guard-doesnt-work%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

                      Use pre created SQLite database for Android project in kotlin

                      Darth Vader #20

                      Ondo