G
G
GF2020-11-07 18:30:57
typescript
GF, 2020-11-07 18:30:57

Omit return type in async method?

https://www.typescriptlang.org/play?#code/JYOwLgpg...

I don't quite understand why the method's return type doesn't validate correctly?

interface User {
  username: string
  password: string
  id: number
}

type UserWithoutPassword = Omit<User, 'password'>

class AuthService {
    async validateUser(username: User['username'], password: User['password']): Promise<UserWithoutPassword> {
        const user: User = {
          id: 1,
          username: 'kek',
          password: 'fdsfsd'
        }

        // I want to return all User interface fields exept password
        // if (user?.password === password) {
        //     const { password, ...userInfo } = user

        //     return userInfo
        // }

        return user // why there is no error, if User !== UserWithoutPassword?
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lynn "Coffee Man", 2020-11-08
@fomenkogregory

Try like this:

type UserWithoutPassword = Omit<User, 'password'> & {
    password?: never
}

In English: the password field is optional, and is of type never. Because no value can be of type never, the only way to satisfy that type is to have no password field at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question