您在这里的目标有点不清楚,但如果我理解正确的话,您实际上想要创建一个可以扩展和用作主 struct 属性的用户界面.这可以通过创建属性类型的实际接口来实现,然后该接口可以用作泛型主 struct 的类型参数.例如,您的代码可以按如下方式编写:
// Extract interface from original type
interface User {
id: number
name: string
}
// Doing the same for conversation in case that needs to be extended
interface Conversation {
id: number
userID: number
message: string
}
// Use a type param to indicate the generic type of user must extend the User interface. With this, anything that extends the User interface can be used
interface MainStructure<TUser extends User> {
user: TUser
conversation: Conversation
}
通过以上设置,MainStructure接口可以创建和使用新接口(或实现基本接口的类).
// New user interface that extends basic with a flag indicate logged in status
interface UserWithLogin extends User {
isLoggedIn: boolean
}
请注意,UserWithLogin扩展了User,这是对MainStructure的类型param()的约束.任何扩展或实现基本用户界面的接口或类都可以用作MainStructure的User属性.
在我们之上:
- 从MainStructure接口的属性类型中提取实际接口.
- 向MainStructure接口添加了类型参数,该接口被约束为扩展或实现步骤1中的用户界面的内容.
- 已将MainStructure的属性更新为类型参数.
- 扩展了基本用户界面,包括用户是否登录.
这一切都很好,但在实际使用中如何将以上所有内容结合在一起呢?简单地说,我们在构建MainStructure对象时提供类型:
// use the typeparam to create main structures for basic
const basicUserMainStructure: MainStructure<User> = {
user: {
id: 123,
name: 'Bloopy'
},
conversation: {
id: 892,
userID: 123,
message: 'syn'
}
}
请注意,如果我们将isLoggedIn:True属性添加到basicUserMainStructure的User属性中,将会出现类型错误.通过使用UserWithLogin类型作为类型参数,我们可以为用户提供该属性并满足所有类型条件.
// user typeparam to create main structures for logged-in users
const loggedInUserMainStructure: MainStructure<UserWithLogin> = {
user: {
id: 456,
name: 'Blumpy',
isLoggedIn: true
},
conversation: {
id: 142,
userID: 456,
message: 'ack'
}
}