具有混合成员类型的泛型TypeScript接口 [英] Generic TypeScript interface with mixed member types

查看:122
本文介绍了具有混合成员类型的泛型TypeScript接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于多个HTML表单,我想配置输入并处理它们的值。我的类型具有以下结构(您可以将它复制到TypeScript Playground http://www.typescriptlang.org/play 以查看它的行为):

  interface InputConfig {
readonly inputType:text 密码| list
只读属性?:ReadonlyArray< string>
readonly cssClasses?:ReadonlyArray< string>
}

接口输入< T扩展InputConfig |字符串|串[]> {
只读用户名:(T& InputConfig)| (T& string)
只读密码:(T& InputConfig)| (T& string)
readonly passwordConfirmation:(T& InputConfig)| (T& string)
readonly firstname:(T& InputConfig)| (T& string)
readonly lastname:(T& InputConfig)| (T& string)
只读兴趣爱好:( T& InputConfig)| (T& string [])
}

type InputConfigs = Inputs< InputConfig> // case 1(见下文)
type InputValues =输入< string |串[]> //情况2(见下文)

const configs:InputConfigs = {
username:{
inputType:text
},
password: {
inputType:password
},
passwordConfirmation:{
inputType:password
},
firstname:{
inputType :text
},
姓氏:{
inputType:text
},
爱好:{
inputType:list


$ b const value:InputValues = {
username:testuser1,
password:test1,
passwordConfirmation:test1 ,
firstname:Tester,
姓氏:1,
爱好:[a,b,c]
}

const username:string = values.username

这种通用方法最重要的优点是 Inputs 接口中的单点命名:名称用户名密码 code>, passwordConfi rmation ,...被两者使用 InputConfigs InputValues 这使重命名变得尽可能简单。



不幸的是,自上次赋值 const username:string = values.username 不被编译器接受:

 输入'string | (string& InputConfig)| (string []& InputConfig)| (string []& string)'不能分配给'string'类型。 
键入'string []& InputConfig'不能分配给'string'类型。

我预计它可以工作,因为我的理解是:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆