【发布时间】:2022-01-30 22:50:54
【问题描述】:
我遇到了一个问题,如何从通用的键类型列表中只选择一项。
我用肮脏的方式解决了它,但我希望用更多的好方法来写。
示例)我想为用户创建 dto,并且选择了一种用户类型,但没有选择其他用户类型。
// here 3 classes
class User { .. }
class IntegrationUser { .. }
class Admin {..}
// and they will be matched with keys
export type UserKeyEntityMap = {
user: User;
admin: Admin;
integration: IntegrationUser;
}
// so user type keys is
type UserKey = keyof UserKeyEntityMap;
export type UserResponseDto {
[ K in keyof UserKeyEntityMap]: UserKeyEntityMap[K];
}
预期工作如下:
// error
const testEmpty = {} as UserResponseDto;
// Success
const testOnlyHasUser = { user: {} as User } as UserResponseDto;
// Success
const testOnlyHasAdmin = { admin: {} as Admin } as UserResponseDto;
// error
const testHaveUserAndAdmin = { user: {} as User; admin: {} as Admin } as UserResponseDto;
// error
const testHaveUserAndAdminAndIntegration = { user: {} as User; admin: {} as Admin; integration: IntegrationUser } as UserResponseDto;
这是我的肮脏解决方案
// this cannot be passed test case: testHaveUserAndAdmin
export type UserResponseDto =
Pick<UserKeyEntityMap, 'user'> |
Pick<UserKeyEntityMap, 'admin'> |
Pick<UserKeyEntityMap, 'integration'>;
有什么漂亮的解决方案?
帮帮我!
【问题讨论】:
-
您在上面创建新对象,而不是设置类型。我看到一个语法错误:
',' expected。应该是:{ user: {} as User, admin: {} as Admin }。关于 dto 创建,我们有两个选择:合并所有属性({...properties from user and admin...})或按类型拆分({user: new User(), admin: new Admin()}) -
@AntonHirov 感谢您的评论。但分号(;)在 Typescript 类型对象中是正确的。我没有说那是集合类型。好吧,也许你误解了 Javascript。
-
@AntonHirov 看到这个:flaviocopes.com/typescript-object-destructuring
标签: typescript generics typescript-generics