我有多个几乎相同的方法,它们的返回类型中只有一个不同的键。有没有办法让它们通用,这样我只需要在通用类型中输入键名?
type IsUsersModuleLockedReturnType = {
isLocked: true,
usersRestriction: Restriction
} | {
isLocked: false,
usersRestriction: null
}
// This type is almost the same as above, but uses different key for restriction. Can I somehow make it generic?
type IsGroupsModuleLockedReturnType = {
isLocked: true,
groupsRestriction: Restriction
} | {
isLocked: false,
groupsRestriction: null
}
对我来说,最好的情况是从方法本身推断密钥,但我不知道如何做到这一点。
public readonly getIsUsersModuleLocked = (): IsUsersModuleLockedReturnType => {
if ('users' in this.restrictions) {
return {
isLocked:true,
usersRestriction: this.restrictions.users
}
} else {
return {
isLocked: false,
usersRestriction: null
}
}
}
打字游戏场链接
您可以使用映射类型来做到这一点
在你的情况下,你可以这样做:
type genericType<T extends string> = ( { isLocked: true } & { [key in T]: Restriction } )
| ( {isLocked: false} & {[key in T]: null} );
type IsUsersModuleLockedReturnType = genericType<"usersRestriction">;