【问题标题】:Typescript different interface depending on function argument打字稿不同的接口取决于函数参数
【发布时间】:2020-11-13 18:54:24
【问题描述】:

我有以下场景,我有 2 个接口:

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

export interface UserModelInterface extends UserInterface {
    password: string
}

我有一种方法:

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()
}

我想要关注:

这是一种通过 ID 获取用户的方法。 sensitive 默认为false 女巫导致密码被排除,所以我使用UserInterface

我现在遇到的问题是,如果有人在true 上设置敏感,那么我需要使用UserModelInterface 而不是UserInterface,因为密码在UserInterface 中被排除在外

这可能吗?

【问题讨论】:

标签: javascript typescript mongoose


【解决方案1】:

感谢@Bergi 为我指明了方向。解决方案是使用重载:

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()
}

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2020-12-28
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多