【发布时间】:2017-08-10 07:09:24
【问题描述】:
我有以下功能:
change(key: keyof McuParams, dispatch: Function) {
/** Body removed for brevity */
}
当我调用函数时...
this.change(VARIABLE_FROM_MY_API, this.props.dispatch)
...我(可以理解)得到以下错误:
Argument of type 'string' is not assignable to parameter of type '"foo" | "bar"'
这是有道理的,因为编译器无法知道我的 API 在编译时发送了什么。但是,user defined type guards 有时可用于在运行时推断类型信息,并通过条件将该信息传递给编译器。
当foo 仅定义为类型(而不是数组)时,是否可以为keyof 字符串类型(例如keyOf foo)编写用户定义的类型保护?如果有,怎么做?
【问题讨论】:
标签: typescript