title: How to deal with union type that has undefined in it?
body: <p>I have this function that used to return <code>UserResponseDto | undefined</code>. Now I want to refactor it so I will be returning <code>UserResponseDto | NotFoundDto</code>. The function <code>this.userService.findOne()</code> is returning <code>Promise&lt;User | undefined&gt;</code>.</p>
  
  <p>Currently I have this:</p>
  
  <pre><code>async findOne (@Param() params): Promise&lt;UserResponseDto | undefined&gt; {
    return this.userService.findOne(params.id)
  }
  </code></pre>
  
  <p>I want something like this:</p>
  
  <pre><code>async findOne (@Param() params): Promise&lt;UserResponseDto | NotFoundResponseDto&gt; {
    const user = await this.userService.findOne(params.id)
    if (typeof user === "undefined") {
      return new NotFoundResponseDto()
    }
  
    return new UserResponseDto(user) // 1
  }
  </code></pre>
  
  <p>But unfortunately I can't seem to get rid of that <code>undefined</code> in <code>User | undefined</code> part. In <code>// 1</code> the <code>user</code> is still treated as <code>User | undefined</code>. Should I use <code>user as User</code>? I feel like it's a nasty workaround though.</p>
  
  <p>Am I missing something? Can it be done easier without a ton of boilerplate code?</p>
  
  <hr>
  
  <p><code>UserResponseDto</code> is a class that takes 1 argument in the constructor <code>user: User</code> and extends <code>SingleResponse&lt;User&gt;</code>.</p>
  
  <hr>
  
  <p>This is another function I'm using that is very similar to this one:</p>
  
  <pre><code>async update (@Param() params, @Body() dto: UpdateUserRequestDto): Promise&lt;User | undefined&gt; {
    const user = await this.userService.update(params.id, dto)
    if (typeof user === 'undefined') {
      return undefined
    }
  
    return this.userService.findOne(user.id) // 2
  }
  </code></pre>
  
  <p>Here I have not gotten around to changing <code>User</code> to <code>UserResponseDto</code> yet and in <code>// 2</code> VS Code is seeing user as <code>User</code>. Not as <code>User | undefined</code> which is exactly what I want from the first function.</p>