我定义了以下内容interface
:
export interface Data {
visibleAction: string
actionsVisibility: {
actionForms: boolean
backButton: boolean
createAccount: boolean
login: boolean
}
actionsHistory: string[]
userID: string
}
稍后在类上实现:
export default class userManager extends Vue implements Data {
actionsVisibility = {
login: false,
createAccount: false,
backButton: false,
actionForms: false
}
visibleAction = `login`
actionsHistory = []
userID = ``
hideUserActionForm () {
this.actionsVisibility[this.visibleAction] = false
}
... other logic
}
对于this.actionsVisibility[this.visibleAction] = false
TS行,警告错误:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ login: boolean; createAccount: boolean; backButton: boolean; actionForms: boolean; }'. No index signature with a parameter of type 'string' was found on type '{ login: boolean; createAccount: boolean; backButton: boolean; actionForms: boolean; }'.
你能建议一下如何处理跟随类型主义:)
this.visibleAction
in userManager
classstring
在您的情况下会得到一个类型,您不能使用string
它this.actionsVisibility
作为计算的属性名称访问,因此会触发错误。
此外,TS设计的局限性是,类属性()visibleAction
不会从基类型()获得上下文类型Data
,因此您需要再次在类中注释类型。如果将鼠标悬停在类属性上,则会注意到某些属性与接口类型不匹配-有关此答案的更多说明。
可能的解决方案
给visibleAction
在Data
和userManager
显式类型keyof Data["actionsVisibility"]
,这是字符串键联盟actionsVisibility
(游乐场):
export interface Data {
visibleAction: keyof Data["actionsVisibility"] // change this type
actionsVisibility: {
actionForms: boolean
backButton: boolean
createAccount: boolean
login: boolean
}
...
}
export default class userManager implements Data {
actionsVisibility = {
login: false,
createAccount: false,
backButton: false,
actionForms: false
}
visibleAction: keyof Data["actionsVisibility"] = `login` // change this type
...
hideUserActionForm() {
this.actionsVisibility[this.visibleAction] = false // works now
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句