简体   繁体   中英

Typescript different interface depending on function argument

I have following scenario, i have 2 interfaces:

export interface UserInterface extends Document {
    email: string,
    role: string,
    created: Date,
    disabled: Boolean,
    author: AuthorInterface
}

export interface UserModelInterface extends UserInterface {
    password: string
}

and i have one method:

public findUserById(_id: mongoose.Types.ObjectId | string, sensitive: Boolean = false): Promise<UserInterface | null> {
    if (sensitive) return User.findOne({ _id }).exec()
    return User.findOne({ _id }, { password: 0 }).exec()
}

I want following:

This is an method that gets an user by ID. sensitive is by default at false witch leads that the password is exluded so i use UserInterface

Problem i have now is if somebody sets sensitive on true then i would need to use UserModelInterface and not UserInterface because password is excluded in UserInterface

Is this possible?

Thank you @Bergi for showing me the direction. The solution is to use overloads:

public findUserById(_id: mongoose.Types.ObjectId | string, sensitive?: false): Promise<UserInterface | null>
public findUserById(_id: mongoose.Types.ObjectId | string, sensitive?: true): Promise<UserModelInterface | null>

public findUserById(_id: mongoose.Types.ObjectId | string, sensitive: Boolean = false): Promise<UserModelInterface | UserInterface | null> {
    if (sensitive) return User.findOne({ _id }).exec()
    return User.findOne({ _id }, { password: 0 }).exec()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM